打印自定義數據類型的名稱和值可以說,我定義的數據類型,如下所示:如何在Haskell
data OP = Plus | Minus | Num Int deriving (Show, Eq)
然後我採取的strings
名單,並獲得各自的列表OP
值是這樣的:
getOp :: [String] -> [OP]
getOp [] = []
getOp (x:rest)
| x == "+" = Plus:(getOp rest)
| isInfixOf "Num" x == True = Num (read (drop 4 x) :: Int):(getOp rest)
| otherwise = "-" = Minus:(getOp rest)
然後我想顯示[OP]
列表,以換行分隔。我已經很容易地使用了Strings列表,但不知道如何處理數據類型列表。
,我有以下結構爲出發點:
showOp :: [OP] -> String
showOp [] = []
showOp (o:os) = (putStr o):'\n':(showOp os)
我知道最後一行是錯誤的。我試圖在第一部分中返回[Char]
,然後返回Char
,然後進行遞歸調用。我嘗試了一些最後一行的其他變體(見下文),但沒有運氣。
showOp o = show o (works but not what I need. It shows the whole list, not each element on a new line
showOp o = putStrLn (show o) (epic fail)
showOp o
| o == "+" = "Plus\n":(showOp os)
| more of the same. Trying to return a [Char] instead of a Char, plus other issues.
而且,我不知道輸出將需要如何爲Num Int
類型不同,因爲我需要顯示類型名稱和值。
一個例子的I/O,這將是這樣的:
在:
getOp ["7","+","4","-","10"]
出來:
Num 7
Plus
Num 4
Minus
Num 10
永遠不要說x ==真。只需說出x。 – augustss