Isaac Spivack
Isaac Spivack

Reputation: 13

Why am I getting a parse error on input '=' Haskell

I am getting a parse error on input '=' when trying to run the following code

module GiveNums
  where
import System.IO

main = do
  hSetBuffering stdin LineBuffering
  n <- giveNum
  sum = map (+) n
  putStrLn "The sum is " ++ show sum

giveNum = do
  hSetBuffering stdin LineBuffering
  putStrLn "Enter num"
  num <- getLine
  if read num == 0
    then return []
  else do
   rest <- giveNum
   return ((read num :: Int: rest)

Upvotes: 1

Views: 1123

Answers (2)

TanasaIoan
TanasaIoan

Reputation: 19

Because if you want to "assign" something in a do statement you need to put let before it, so sum = map (+) n turns into let sum = map (+) n, but as wizzup pointed out sum is already defined as a standard function and also let sum = map (+) n wont return the sum of integers in n , for that you would need foldr

let sumOfn = foldr (+) 0 n

But it would be easier to do let sumOfn = sum n Also, let f =map (+) n creates a list of functions of type Int->Int, if n is [1,2,3] then f is [(+1),(+2),(+3)].

Upvotes: 0

wizzup
wizzup

Reputation: 2411

To answer your question: because your code has syntax error.

Some additional comments:

  1. You don't need module when working with a single code file. module is for writing a library.

  2. Bindings in main :: IO () need let because it is in the IO Monad. Read more about do here

  3. Setting stdin buffering mode only once is enough.

  4. There is a sum function in Prelude.

I tried to make the code as close to the original as possible. However, this is not good Haskell code.

import System.IO

main :: IO ()
main = do
  hSetBuffering stdin LineBuffering
  n <- giveNum
  let summation = sum n
  putStrLn $ "The sum is " ++ show summation

giveNum :: IO [Int]
giveNum = do
  putStrLn "Enter num"
  num <- read <$> getLine

  if num == 0
    then return []
    else do
         rest <- giveNum
         return $ num: rest

Output:

$ runhaskell givenum.hs 
Enter num
1
Enter num
2
Enter num
3
Enter num
0
The sum is 6

Upvotes: 1

Related Questions