0

Need help with a haskell problem thats doing my head in. I know the steps (sorta) that need to be taken to achieve want I want but I don't really know how to go about doing it.

E.g

Say I have a lists of Maybe Int's - [[Just 2, Nothing, Just 3],[Just 6,Just 3, Just 3],[Nothing,Nothing, Just 1]]

I need to create a function that.

1) Takes lists of Maybe Ints

[[Just 2, Nothing, Just 3],[Just 6,Just 3, Just 3],[Nothing,Nothing, Just 1]]

2) Gets First List (head?)

[Just 2, Nothing, Just 3]

3) Recurse through each element within the list - (x:xs)

Just 2, Nothing, Just 3

4) convert Maybe Int to a Char - fromEnum

'2', '   ', '3'

5) return the complete String containing all the chars - (++) = [char] / String

"2   3"

6) move onto the next List until list = []

[Just 6,Just 3, Just 3]

So the end result would be something like this printed out on a separate line:

"2   3"
"633"
"     1"

I tried to explain it as well as possible and any tips / helps / sources of information would be appreciated.

1
  • Just FYI, you keep saying you want to operate on a list of Maybe Ints, but your examples each have Lists of List Maybe Int. Ie [[Maybe Int]] Commented Mar 15, 2012 at 9:46

1 Answer 1

9

You can use the maybe function, which allows you apply a function to the value in a Just with a default if it was Nothing, so to convert a Maybe Int to a single-digit Char with space as the default, use maybe ' ' intToDigit. (toEnum would use the ASCII value, which is not what you want here).

Then, to apply that within a list of lists, you just use map twice:

> import Data.Char
> map (map $ maybe ' ' intToDigit) [[Just 2, Nothing, Just 3],[Just 6,Just 3, Just 3], [Nothing, Nothing, Just 1]]
["2 3","633","  1"]

Since a string is just a list of characters, the result is a list of strings.

Sign up to request clarification or add additional context in comments.

1 Comment

After you're done, you print it with unlines. So the whole thing should be unlines. map (map $ maybe ' ' intToDigit) $ [your list]

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.