2

I am new to Haskell and I am trying to get a list of values from input and print one item out from the list each line.

func :: [String] -> IO ()

I am having trouble trying to figure out how to print out the item in the list, when the list size is just 1.

func [] = return ()  
func [x] = return x

I am getting this error message when trying to compile the file:

Couldn't match expected type `()' with actual type `String'
    In the first argument of `return', namely `x'
    In the expression: return x

I am completely lost and I have tried searching but haven't found anything. Thanks!

1
  • 2
    You're not actually printing anything if you just return a value. You need a function like putStrLn for that. Commented Apr 1, 2013 at 14:20

3 Answers 3

9

You can use forM_ for this:

func :: [String] -> IO ()
func l = forM_ l putStrLn

If you want to write your own version directly, you have some problems.

For the empty list, you have nothing to do but create a value of IO (), which you can do with return.

For the non-empty list you want to output the line with putStrLn and then process the rest of the list. The non-empty list is of the form x:xs where x is the head of the list and xs the tail. Your second pattern matches the one-element list.

func [] = return ()
func (x:xs) = putStrLn x >> func xs
Sign up to request clarification or add additional context in comments.

1 Comment

If you prefer the 'origami programming' style, your second implementation could be written as foldr (\s m -> putStrLn s >> m) (return ()), or even foldr ((>>) . putStrLn) (return ()), which I think is rather pretty :)
8
func = mapM_ putStrLn

mapM_ applies a monadic function like putStrLn to each element of a list, and discards the return value.

Comments

7

you actually aren't trying to print anything, you use putStr for that. try something like

print [] = return ()
print (x:xs) = do
                 putStr x
                 print xs

2 Comments

Thanks. That actually makes a lot of sense. :)
Be aware there's already a function named print in the Prelude: hackage.haskell.org/packages/archive/base/latest/doc/html/…

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.