0

I want to take first three elements from user input in Haskell, but I got error message. Thank you for the help

 getCmd cmd = do
    putStrLn take 3 cmd 

 main = do 
    putStrLn "please type something"
    name <- getLine
    if name /= "QUIT" then do 
        getCmd(name)
        main
    else
        return()
3
  • 1
    You should always post your error message. Regardless, you're typing like you're in Java or C. For instance, replace getCmd(name) with getCmd name... Commented Nov 27, 2014 at 19:35
  • 4
    You need to change the body of getCmd to be putStrLn $ take 3 cmd Commented Nov 27, 2014 at 19:35
  • @Lee Hi lee I am new for haskell. Could you tell me what is the "$" mean? thank you Commented Nov 27, 2014 at 19:38

1 Answer 1

3

Your definition of getCmd should be:

getCmd cmd = do
    putStrLn (take 3 cmd)

function application is left-associative so your definition is parsed as

(((putStrLn take) 3) cmd)

so you need to add the brackets so putStrLn is applied to the result of applying take.

Haskell also defines the $ infix operator which has a lower precedence than function application so it is commonly used instead of using brackets. Your use of do is also redundant so you can define getCmd as

getCmd cmd = putStrLn $ take 3 cmd

or even

getCmd = putStrLn . take 3
Sign up to request clarification or add additional context in comments.

1 Comment

Another enhancement is to use when from Control.Monad as it's exactly an if with return () in else branch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.