I have list of lists and the result should be, list of list with the factorial applied to each element.
[[1,2],[3,4],[3],[1,1,1]]=[[1,3],[6,24],[6],[1,1,1]]
code for factorial for one list:
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n *factorial (n-1)
fun x = map factorial x
CodePudding user response:
I assume you just want to apply the factorial
function to each element of each sublist of the list. Fortunately, it’s a very common pattern in Haskell to map a function over another function. To do that, you use the higher-order function map
. map
takes a function and a list and returns a list where every element is the result of the function applied to the corresponding input list’s element.
But what do you do if you want to map it over a nested list? You’d like to map the mapping. This is possible because Haskell allows you to partially apply functions. You can omit an argument, and you get a function with the other arguments pre-filled. For instance, if foo x y = x y * y
, foo 2
is a function, too, that takes another value, and the result of (foo 2) z
is 2 z * z
. So you can also write map factorial
without the list at the end to mean the mapping.
And then, the solution is:
factorialsOnNestedList list = map (map factorial) list
…but you can η-reduce this to factorialsOnNestedList = map $ map factorial
CodePudding user response:
Well, you as you've shown in your question, you know how to find the factorial for every element of a list:
fun x = map factorial x
(Side note: whenever you have the pattern function arg = someOtherFunction arg
, you can just write function = someOtherFunction
- in this case,
fun x = map factorial x
becomes
fun = map factorial
)
So if you have a nested list, you want to apply fun
to every list inside the nested list. What can you use for that? map
again
funNested nestedList = map fun nestedList
-- Or, by removing `nestedList`:
funNested = map fun