Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell iterate over a list

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

like image 939
nobody Avatar asked Nov 28 '22 03:11

nobody


2 Answers

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
like image 146
ivanm Avatar answered Dec 04 '22 10:12

ivanm


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
like image 24
franza Avatar answered Dec 04 '22 08:12

franza