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
Run Code Online (Sandbox Code Playgroud)
It works just for basic operations. However, I came to realize that I need to have the signature defined as
String -> String
Run Code Online (Sandbox Code Playgroud)
not String -> [Double]. So the calculation result for "1 2 +" should be
"[3.0]"
Run Code Online (Sandbox Code Playgroud)
instead of
[3.0]
Run Code Online (Sandbox Code Playgroud)
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!
The only problem is that you are trying to show the calc function, not its result.
calcK :: String -> String
calcK = show . calc
Run Code Online (Sandbox Code Playgroud)
You want to compose show and calc, letting calc produce a [Double] which is then passed to show.
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |