我有一個小程序,它採取布爾,數字,字符串中的任何一個,並呈現爲一個字符串。渲染數字,布爾,字符串作爲字符串在haskell失敗
module Main() where
data Value = Number Int
| Bool Bool
| String String
deriving (Eq, Show)
renderValue :: Value -> String
renderValue (String s) = show s
renderValue(Bool True) = "true"
renderValue(Number n) = show n
main = do
putStrLn $ renderValue "bye, saravana"
renderValue是一個重載的方法,應該採取字符串輸入。但最後一行,
putStrLn $ renderValue "bye, saravana"
打印誤差,
Couldn't match expected type ‘Value’ with actual type ‘[Char]’
In the first argument of ‘renderValue’, namely ‘"bye, saravana"’
In the second argument of ‘($)’, namely
‘renderValue "bye, saravana"’
In a stmt of a 'do' block: putStrLn $ renderValue "bye, saravana"
爲什麼Value = Number | Bool | String
不採取串投入? Number
,Bool
和String
:
'renderValue'需要一個'Value'參數而你正在嘗試提供一個'String'(它是'[Char]'的別名)。你需要使用'renderValue(String「bye,saravana」)''。 – Lee
@Lee您應該將其作爲答案發布。 – Sibi
我試過了,'renderValue([Char] s)= show s'。它在[Char]上解析錯誤失敗。然後,我試着'導入Data.Char'和'renderValue(Char s:xs)= show s'。它仍然抱怨,'不在範圍內:數據構造函數'Char'' .... –