开发者

how to write return Haskell

开发者 https://www.devze.com 2023-01-04 18:27 出处:网络
I want my showStackHead function take a stack print the head and return the rests, here is my code --code

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 thi开发者_运维问答s function?


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

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号