After having a look at these two threads: Does F# have an equivalent to Haskell's take? , Take N elements from sequence with N different indexes in F# , I've been wondering about the best way to use sequence operators on lists or even if using them.
I am at the moment a newbie at F# and I'm writing a program which has to deal with lots of sequences that I get from HtmlAgilityPack. There are some interesting operators in the Seq module but as stated in those threads, it might be poor related to performance and if we are obliged to constantly converting between seq -> list it also clutters code with things that are not problem-solving... which is why I started learning F# in the first place.
A simple example is when I need to take 'N' elements of a list:
listOfRows
|> Seq.take 2
// Now I don't have a list anymore, it returns a sequence
|> List.ofSeq
So, could anyone shed some light about the best way to deal with these scenarios? I can work solutions using Seq.take and Seq.skip but this is known to be very inefficient. On the other hand it's a shame to have the functionality built into the standard library and having to reimplement it for using the same concept on a different collection, or make the code dirtier with explicit conversions.
How could I see the performance impact each conversion between 'list -> seq' and 'seq -> list' has?
Thanks a lot.
Some of this might depend on exactly how you want to use all this end-to-end.
In many cases it will be fine to convert to a list once up front, and then only use the List operators to map/traverse/etc. There may not be a List.take
, but that's because with lists, if you know there are going to be at least two elements and you want to grab those two, you can do it with a pattern match, e.g.
let (item1::item2::rest) = someList
So I suspect that may be what you want to do in this scenario (I expect with HTML parsing, you might have some kind of expected rough schema of elements you're looking for, etc.).
(If laziness/streaming is essential, then Seq becomes much more useful.)
Briefly, the commonest operators (like map
) are on all the collection types (Seq
, List
, Array
, ...) whereas the uncommoner ones (like take
) are only available on Seq, often because there are better ways to do things when you have a concrete type (e.g. list pattern matching to take the first items).