0

For this function,showGame, and the expected output, anyone can give me a hand to make this work ?

import System.IO  

type Symbol = Int  

showGame :: [Symbol] => IO ()  
showGame xs =   
    let x = mapM_ (replicate '*') xs  
    putStrLn x  

The output should be:

1: *  
2: **  
3: ***  

with

 [Symbol] = [1,2,3]  
1
  • Functions named show in Haskell typically provide a String rather than an IO action. You might want to name this printGame instead. Commented Nov 27, 2013 at 3:12

2 Answers 2

3

After fixing a few mistakes in your code we get this:

type Symbol = Int  

showGame :: [Symbol] -> IO ()  
showGame xs =
  mapM_ (\x -> putStrLn $ show x ++ ": " ++ replicate x '*') xs

main = showGame [1..3]

Output:

1: *
2: **
3: ***
Sign up to request clarification or add additional context in comments.

1 Comment

This is also a good place to use forM (mapM with the arguments flipped) because then it reads like a foreach loop.
1

It looks like you want:

let x = fmap (flip replicate $ '*') [1,2,3]
mapM_ putStrLn x

mapM_ applies a monadic action over a list but discards the results. This is what you want to print, since there is no useful result. However you do want the a result when creating the lists to display. Here you can just use fmap (or map since the input is a list) to create a list for each input list element.

1 Comment

I'd say (`replicate` '*') is significantly more readable than the equivalent with flip, and in fact easier to understand (though it actually uses more advanced features of the language).

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.