Search code examples
functionhaskelllambdatuplesfoldleft

Haskell-- Trying to make my foldl function work


I have a function that converts [a, b, c, d, . . . ] to [(a,b), (c, d), . . .]. Now this works and here is the code for that:

makeTuple :: [a] -> [(a,a)]
makeTuple [] = []
makeTuple [a] = []
makeTuple (x:y:xs) = (x,y): (makeTuple xs)

Now the next thing I have to do is this: Using the previous function, convert each tuple to a product of its two elements, using foldl and a lambda expression. And this is what I have:

productTuple [x] = foldl makeTuple [] [x]

Now I am not sure if this is exactly what is being asked of me. I'm not sure if I should make a separate function with the type declaration and whatnot. Maybe someone can tell me if that is the best way to approach this. Also this code does not work, and I don't know why,I need help with this part. (notice that it says to use a lambda, but I have no idea how to really properly use those, which is another part I need help with) I would really appreciate it, thanks.


Solution

  • The lambda function should respect this signature :

     [a] -> (b,b) -> [a]
    

    The accumulator has the type [a], the tuple has the type (b,b)

    You can try a lambda like this \acc (a, b) -> acc++[a*b]

    The final function could look like :

    productTuple :: Num a => [a] -> [a]
    productTuple xs = foldl (\acc (a, b) -> acc++[a*b]) [] (makeTuple xs)
    

    You have some examples of foldl function here

    I tried this code here