tags:

views:

181

answers:

2

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?

+14  A: 

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

showStackHead xs
   | xs == []   = return []
   | otherwise  = do putStrLn ("result:" ++ (head xs))
                     return (tail xs)
Don Stewart
read about "layout" in the Haskell 98 tutorial
bandi
+2  A: 

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
dino