Try this:

let len l = l |> Seq.fold (fun acc _ -> 1 + acc) 0

Just start with 0 and add one for every element in the sequence.
Should work for any sequence type...

By on 6/6/2010 6:18 PM ()

Try this:

let len l = l |> Seq.fold (fun acc _ -> 1 + acc) 0

Just start with 0 and add one for every element in the sequence.
Should work for any sequence type...

I was trying something sort of between your answer and Mau's and couldn't quite make that last leap of intuition. :-) Thanks.

By on 6/7/2010 5:07 AM ()

Apply '+', start from 0:

1
collection |> Seq.fold (+) 0

:-)

By on 6/7/2010 12:39 AM ()

Apply '+', start from 0:

1
collection |> Seq.fold (+) 0

:-)

Hi Mau,

This [i]sums[/i] the elements in the list. I was trying to get a count of how many elements are in the list.

By on 6/7/2010 6:40 AM ()

Ouchi, I'm sorry, I misread.

By on 6/7/2010 7:52 AM ()

minor comments:

FP purists would advice you NOT to use recursion if possible and use the higher order function like fold or unfold instead. Try to watch those Channel 9 video by Eric Meijer and you would get that impression.

'fold' in F# is 'left fold' which is straightly speaking not a true 'loop' equivalent. a lazy 'right fold' as far as I know can do anything a loop can.

That said, I found recursion easier to work with :-)

gary

PS. search 'graham hutton' if you want to learn about fold, his papers in this subject are eye opening.

By on 6/7/2010 2:00 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper