Search code examples
haskelliofunctional-programmingguard

Haskell mutliline guard inside do not working


Hello I am new to Haskell and I think that my problem is simple but important for me.

This works:

module Main where

main :: IO ()
main = do
    inp <- getLine
    let output i | odd i = "Alice" | even i = "Bob" | otherwise = "Weird"
    putStrLn (output (read inp))

This does not work

module Main where

main :: IO ()
main = do
    inp <- getLine
    let output i 
        | odd i = "Alice" 
        | even i = "Bob" 
        | otherwise = "Weird"
    putStrLn (output (read inp))

What I know: Inside do you write "lets" or "let" before every function you declare and you do not write "in". Also when I wrote output as a non local function it worked.

What have I missunderstood?

edit: would you recommend writing like this?

module Main where

main :: IO ()
main = do
    inp <- getLine
    let
        output i 
            | odd i = "Alice" 
            | even i = "Bob"
    putStrLn (output (read inp))

Solution

  • You need to indent the guards (with at least one extra space compared to the position of output), for example:

    main :: IO ()
    main = do
        inp <- getLine
        let output i 
                | odd i = "Alice" 
                | even i = "Bob" 
                | otherwise = "Weird"
        putStrLn (output (read inp))

    Since a number is either odd or even, you can just use otherwise for the even case:

    main :: IO ()
    main = do
        inp <- getLine
        let output i 
                | odd i = "Alice" 
                | otherwise = "Bob"
        putStrLn (output (read inp))