How to properly implement reduce function in F#

Viewed 317

I am pretty new to F# and learning lists.I am having a hard time trying to implement my own reduce function. I've been stuck trying to implement this one. This is what I have so far but I am getting an error that when calling reduce saying that the list i pass in is type is type int but should be type 'a list. I've been super frustrated with this one so any help is welcome.

Here is what my code looks like:

let reduce Fn (list: 'a list) = 
      let rec innerFun list acc =
          match list with
          | (x::xs) :: xss ->
              let newAcc = Fn x xs // the fn applied to the head and the next element
              innerFun xss newAcc // recurse through the list with new accumulator
          | [] -> acc // if the list is empty return the accumulator
      innerFun list 0 
               
   //Calling reduce            
   let red2 = reduce (fun x y -> x*y) [23; 4]

1 Answers

The immediate problem you have is actually quite simple and purely syntactical:

match list with
| (x::xs) :: xss ->

The parentheses make it so that the pattern is matching a list of lists, i.e. x::xs is the head element of the list, and x and xs are respectively its head and tail.

What you want is to match two elements in the front of the list - you need to drop the parens:

match list with
| a::b::tail ->

Note that the naming convention you're using already has a hint in it - the s in xs is for plural - so in that pattern you split a list into a head of "ex" and a tail of "exes".

Related