5

I want my showStackHead function take a stack print the head and return the rests, here is my code --code

showStackHead xx
               | xx == []   = return []
               | otherwise  = do putStrLn("result:" ++ (head xx))
                              return (tail xx)

when I run this code, the compiler tells me there is a parse error about the second return, so what is the right way to write this function?

2 Answers 2

15

Indent the 'return' to the same depth as 'putStrLn', like so:

showStackHead xs
   | xs == []   = return []
   | otherwise  = do putStrLn ("result:" ++ (head xs))
                     return (tail xs)
Sign up to request clarification or add additional context in comments.

Comments

2

As an aside, your showStackHead could be cleaner by using pattern matching. Allowing you to ditch the guard comparison, head and tail:

#! /usr/bin/env runhaskell


showStackHead []     = return []
showStackHead (x:xs) = do
   putStrLn $ "result: " ++ [x]
   return xs


main :: IO ()
main = do
   let s1 = []
   r1 <- showStackHead s1
   putStrLn $ "returned: " ++ r1

   putStrLn "---"

   let s2 = "foo"
   r2 <- showStackHead s2
   putStrLn $ "returned: " ++ r2

   putStrLn "---"

   let s3 = "q"
   r3 <- showStackHead s3
   putStrLn $ "returned: " ++ r3

Comments

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.