I agree that this solution seems invalid.
The superficial problem is sampleInput is supposed to be ["21", "+", "123"], but is actually ["21 + 123"]. Without changing the signature of calc:
import Data.List.Split
calc :: [String] > Int
calc (val1:"+":val2:rest) = read val1 + read val2
calc (val1:"*":val2:rest) = read val1 * read val2
main :: IO ()
main = do
userInput < getContents
let expressions = (concatMap $ splitOn " ") . lines
let values = expressions userInput
print (calc values)
This lazily evaluates, but doesn't allow multiple expressions.
So, maybe the author meant:
import Data.List.Split
calc :: [String] > Int
calc (val1:"+":val2:rest) = read val1 + read val2
calc (val1:"*":val2:rest) = read val1 * read val2
main :: IO ()
main = do
userInput < getContents
let expressions = map (splitOn " ") . lines
let values = expressions userInput
print (map calc values)
This allows multiple expressions, but doesn't lazily evaluate (I think due to `print [a]`, but I don't understand why that happens).
Based on this theory, I tried:
import Data.List.Split
calc :: [String] > Int
calc (val1:"+":val2:rest) = read val1 + read val2
calc (val1:"*":val2:rest) = read val1 * read val2
main :: IO ()
main = do
userInput < getContents
let expressions = map (splitOn " ") . lines
let values = expressions userInput
mapM_ print (map calc values)
Which seems to completely satisfy the original problem definition:
$ stack ghc simple_calc2.hs
$ ./simple_calc2
1 + 2
3
3 + 4
7
8 * 8
64
