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!
As mentioned by Vidas, you can just use the built-in
List.lengthfunction, 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:This is not written using combinators, but it's a basic functional pattern. The general pattern of the function is captured by the
foldfunction, which lets you (basically) specify the two branches of the pattern matching. Usingfoldyou can write:This says that the initial state is
0and, for every element, we increment the statesby1- 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 + 1with 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: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.
So,
List.lengthis the way to go :-).