How to write return Haskell

I want my showStackHead function to take a stack by typing head and returning leftovers, 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 that there is a parsing error in the second return, so what is the correct way to write this function?

+5
source share
2 answers

Pull back 'return' to the same depth as putStrLn, for example:

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

As an aside, your showStackHead can be cleaner using pattern matching. Letting you compare the 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
+2
source

All Articles