Thursday, May 3, 2012

Playing with Haskell: Multiplication Tables

After reading I'm a list comprehension in Learn You a Haskell for Great Good! book, it came to my mind that I could generate multiplication tables as an initial exercise.
After a bit of trial and error, I managed to group the lists the way I wanted.
This is my clumsy solution:
mulTable n = [[c * b | b <- xs] | c <- [0..n]] !! n
    where 
        xs = [0..10]
And this is how it's used:
*Main> :l baby.hs 
[1 of 1] Compiling Main             ( baby.hs, interpreted )
Ok, modules loaded: Main.
*Main> mulTable 0
[0,0,0,0,0,0,0,0,0,0,0]
*Main> mulTable 1
[0,1,2,3,4,5,6,7,8,9,10]
*Main> mulTable 2
[0,2,4,6,8,10,12,14,16,18,20]
*Main> mulTable 7
[0,7,14,21,28,35,42,49,56,63,70]
*Main> mulTable 10
[0,10,20,30,40,50,60,70,80,90,100]
*Main> mulTable 12
[0,12,24,36,48,60,72,84,96,108,120]
*Main> mulTable 15
[0,15,30,45,60,75,90,105,120,135,150]
*Main> mulTable 20
[0,20,40,60,80,100,120,140,160,180,200]
@remosu has a simpler and better solution:
mulTable n = [c * n | c <- [1..10]]
and he did it also in python:
multable = lambda n: [c * n for c in range(1, 11)]

No comments:

Post a Comment