I would like to understand if it is possible in Haskell to somehow display the list element by element, that is, an analogue of such code in Java

for(String s: string_array){ System.out.println(s); } 

I read the books - I found the following solution:

 printList list = case list of [] -> putStrLn "" (x:xs) -> do putStrLn $ show x printList xs 

    3 answers 3

    Phased improvement ("ukaskelenie") solutions:

    0. Add signature

     printList :: [String] -> IO () printList list = case list of [] -> putStrLn "" (x:xs) -> do putStrLn $ show x printList xs 

    1. Disappears case:

     printList :: [String] -> IO () printList [] = putStrLn "" printList (x:xs) = do putStrLn $ show x printList xs 

    2. Disappears do:

     printList :: [String] -> IO () printList [] = putStrLn "" printList (x:xs) = (putStrLn $ show x) >> printList xs 

    3. Explicit recursion disappears (true, the empty line at the end disappears too):

     printList :: [String] -> IO () printList = mapM_ $ putStrLn . show 

    4. Generalization from lines to any objects to which show can be applied:

     printList :: Show a => [a] -> IO () printList = mapM_ $ putStrLn . show 

    5. The expression putStrLn . show putStrLn . show equivalent to the print function.

     printList :: Show a => [a] -> IO () printList = mapM_ print 

    If anyone is interested, I can break the point "3." into smaller steps.

      You can still like this if you have a list of strings

       printList::[String]->IO () printList = putStrLn.unlines 

      or like this for an arbitrary type implementing Show

       printList::Show a => [a] -> IO () printList = putStrLn.unlines.map show 

        A literal translation of the above Java code, two options:

         mapM_ print [1,2,3,4] forM_ [1,2,3,4] print