Getting the length of a list using combinators f#

338 Views Asked by At
let length (l : 'a list) =
  let mutable counter = 0
  for i in l do
    counter <- counter + 1
  counter

let list1 = [ 10; 25; 34; 45; 78 ]
length list1

I can get the length of a list using the above piece of code (in F#) but I'm wondering how I can do this exact code using combinators. If anyone could help out that'd be great, thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

As mentioned by Vidas, you can just use the built-in List.length function, which is the best way to do this in practice. However, if you are interested in more options, then the basic alternative is to use recursion:

let rec length l = 
  match l with 
  | [] -> 0
  | x::xs -> 1 + (length xs)

This is not written using combinators, but it's a basic functional pattern. The general pattern of the function is captured by the fold function, which lets you (basically) specify the two branches of the pattern matching. Using fold you can write:

let list1 = [ 10; 25; 34; 45; 78 ]
List.fold (fun s x -> s + 1) 0 list1

This says that the initial state is 0 and, for every element, we increment the state s by 1 - so the result will be the length of the list.

If you wanted to do something completely crazy, you could try to replace the function fun s x -> s + 1 with a function composed using combinators. This will make your code unreadable (and nobody should ever do this), but it's fun to think how to do this. You might need a helper function that takes a function, two arguments and passes the two arguments to the function as a tuple:

let tuple f = fun a b -> f (a, b)

Now you can write something like the code below - which is as using as much combinator style as possible, but it's pretty hard to decipher.

List.fold (tuple (fst >> (+) 1)) 0 list1

So, List.length is the way to go :-).

1
On

I assume you are asking for

Seq.length list1