patternMinor
Multiplication table using a list comprehension
Viewed 0 times
comprehensionmultiplicationusinglisttable
Problem
I have just started reading through Learn you a Haskell I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number
the actual function/list comprehension I came up with is
Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know.
n and an upper limit upperLimit and return a nested list of all the 'tables' up to n for example> timesTable 2 12
[[1,2..12],[2,4..24]]the actual function/list comprehension I came up with is
> let timesTable n upperLimit = [[(n-y) * x | x <- [1..upperLimit]] | y <- reverse [0..(n-1)]]Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know.
Solution
Your function could be simplified a little, and I find it helpful to define functions using declarations, since type signatures are really helpful (although admittedly your example is simple enough that it doesn't matter):
The key thing I noticed was that you were using
timesTable :: Int -> Int -> [[Int]]
timesTable n u = [[y * x | x <- [1 .. u]] | y <- [1 .. n]]The key thing I noticed was that you were using
n-y: it should be obvious that this part of the expression becomes the following values in each iteration of y: [n-(n-1), n-(n-2), ... n-0], which is just [1 .. n].Code Snippets
timesTable :: Int -> Int -> [[Int]]
timesTable n u = [[y * x | x <- [1 .. u]] | y <- [1 .. n]]Context
StackExchange Code Review Q#8421, answer score: 5
Revisions (0)
No revisions yet.