Kevin
Kevin

Reputation: 6831

How to change the function signature

I am a beginner to Haskell and is now trying to develop a postfix calculator. Below is my code so far:

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

It works just for basic operations. However, I came to realize that I need to have the signature defined as

   String -> String

not String -> [Double]. So the calculation result for "1 2 +" should be

  "[3.0]"

instead of

   [3.0]

As you can see, I've tried to do a show at the top but it does not seem to be working. I've tried adding show to other places of the code but still no luck.

Would be grateful if experts could offer some advice on this. Thanks in advance!

Upvotes: 3

Views: 119

Answers (1)

chepner
chepner

Reputation: 532218

The only problem is that you are trying to show the calc function, not its result.

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

You want to compose show and calc, letting calc produce a [Double] which is then passed to show.

Upvotes: 7

Related Questions