I know you suppose to think differently in Haskell, but can someone give me a quick answer on how to iterate over a list or nested list and print out a character based on the value of the list element.
list1 = [[1 0 0][0 1 0][0 0 1]]
By iterate through this nested list, it should print out x for 0 and y for 1
yxx
xyx
xxy
Thanks
First of all, I think you mean:
list1 :: [[Int]]
list1 = [[1,0,0],[0,1,0],[0,0,1]]
As for what you want:
valueOf :: Int -> Char
valueOf 0 = 'x'
valueOf 1 = 'y'
valueOf _ = 'z'
listValues :: [[Int]] -> [String]
listValues = map (map valueOf)
printValues :: [[Int]] -> IO ()
printValues = putStrLn . unlines . listValues
And then in ghci:
*Main> printValues list1
yxx
xyx
xxy
Try this:
fun :: [[Int]] -> [String]
fun = (map . map) (\x -> if x == 0 then 'x' else 'y')
If you really need printing of result:
printSomeFancyList :: [[Int]] -> IO ()
printSomeFancyList = putStrLn . unlines . fun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With