Applying putStr to Each List Item

I am trying to print a list of integers in this format

[1] [2] [3] 

So my function takes a list of integers and returns IO () as follows:

 import System.IO printVector :: [Integer] -> IO () printVector (x:xs) = putStr("[" ++ show(x) ++ "]" ++ "\n") : printVector xs 

But ghc gives me an error:

 lin-test.hs:5:22: Couldn't match expected type `IO ()' with actual type `[a0]' In the expression: putStr ("[" ++ show (x) ++ "]" ++ "") : printVector xs In an equation for `printVector': printVector (x : xs) = putStr ("[" ++ show (x) ++ "]" ++ "") : printVector xs Failed, modules loaded: none. 

Now I understand that the function will be executed through the list, first taking the first element "x", and then using: printVector xs it will recursively call the rest of the list, applying the same putStr function to each element in the list.

But I think my problem is where I am doing: printVector xs? Can someone point out what I'm doing wrong here?

+8
list printing haskell
source share
1 answer

You need to display the list, but since these are I / O operations, you also need to execute them (since map will return a list of I / O operations without them, see the following example).

 sequence $ map (putStrLn . show) [1,2,3,4] 

There is a function that already does this, mapM . Thus, an example can be simplified as:

 mapM (putStrLn . show) [1,2,3,4] 

Another thing you can do is use mapM_ , which instead uses sequence_ and will ignore the result of the IO action for each of the elements. Therefore, the return type will be IO () instead of IO [()] (previous example).

 mapM_ (putStrLn . show) [1,2,3,4] 
+14
source share

All Articles