2
votes

I'm supposed to write a function that will contain the product of each previous multiplication with that number

Basically this:

> productFromLeftToRight [2,3,4,5]
[120,60,20,5]

I'm supposed to use High Order functions, so folds and such. I'm thinking of using a foldr to traverse through the list with a lambda expression. This is what I'm thinking:

> productFromLeftToRight nums = foldr (\x acc -> [x] * acc ++ acc) [] nums

Since it would unravel like f(2 (f 3 (f 4 (f 5 [])))) I would think I'm right, but I get the whole print error and I don't know how to multiply a number with the first element of acc ( head acc doesn't work)

3

3 Answers

4
votes
productFromLeftToRight = scanr1 (*)

or

productFromLeftToRight' = 
  snd . foldr (\x (acc,lst) -> (x * acc, x * acc : lst)) (1,[])
2
votes
productFromLeftToRight nums =
    init $ foldr (\x lst -> x * head lst : lst) [1] nums

The idea is to use a dummy element 1 to the answer list and remove it in the end.

0
votes

Here's another one that doesn't do any post-processing after the foldr:

productFromLeftToRight = foldr (\n ps -> n * foldr const 1 ps : ps) []

Here, the inner foldr const 1 is acting as a non-partial head function to get the first element of ps:

foldr const 1 (x:xs) = const x (foldr const 1 xs) = x
foldr const 1 []     = 1