如何更改功能签名

时间:2019-07-06 15:06:58

标签: haskell

我是Haskell的初学者,现在正在尝试开发后缀计算器。 下面是到目前为止的代码:

calcK :: String -> String
calcK =  show calc

calc :: String -> [Double]
calc = foldl interprete [] . words

interprete s x
  | x `elem` ["+","-","*","/","^"] = operate x s
  | x `elem` ["inc","dec","sqrt","sin","cos","inv"] =  operate2 x s
  | x `elem` ["+all"] =  [sum s]
  | x `elem` ["*all"] =  [product s]
  | otherwise = read x:s
  where
    operate op (x:y:s) = case op of
      "+" -> x + y:s
      "-" -> y - x:s
      "*" -> x * y:s
      "/" -> y / x:s
      "^" -> y ** x:s
    operate2 op (x:s) = case op of
      "inc" ->1 + x:s
      "dec" -> (-1) + x:s
      "sqrt" -> sqrt x:s
      "sin" -> sin x:s
      "cos" -> cos x:s
      "inv" -> 1 / x:s

它仅适用于基本操作。但是,我意识到我需要将签名定义为

   String -> String

不是String -> [Double]。因此"1 2 +"的计算结果应为

  "[3.0]"

代替

   [3.0]

如您所见,我尝试在顶部执行show,但似乎没有用。我尝试将show添加到代码的其他位置,但还是没有运气。

如果能就此提出一些建议,将不胜感激。预先感谢!

1 个答案:

答案 0 :(得分:7)

唯一的问题是您试图显示calc函数,而不是其结果

calcK :: String -> String
calcK = show . calc

您想组成showcalc,让calc产生[Double],然后将其传递给show