Thomas
Thomas

Reputation: 12107

checking if enough elements in a F# list

Right now I have a few instances like this:

let doIt someList =

    if someList |> List.truncate 2 |> List.length >= 2 then
        someList[0] + someList[1]
    else
        0

I need to grab the top 2 elements of a list quite often to see changes, but in some cases I don't have enough elements and I need to make sure there are at least 2. The best way I've found so far is to truncate the list before getting its length, but this creates allocations for no reason.

Is there a better method?

Upvotes: 1

Views: 68

Answers (1)

Caramiriel
Caramiriel

Reputation: 7257

I think I would suggest pattern matching in this case:

let doIt someList =
    match someList with
    | a :: b :: _ -> a + b
    | _ -> 0

Here, a and b are the ints in the list, while _ represents a discarded of list int. This way you don't have to pull the first two elements out of the list with an index, as they are already available as a and b. The last case of the match catches any pattern that was not matched earlier, such as cases with zero, one or three-or-more elements.

This should be a cheap operation, as F# lists are implemented as a singly linked list. So [a;b;c;d] would be represented as a::(b::(c::(d::[]))). a and b are matched, while the rest (c::(d::[])) is left untouched (and is put in the _ slot). It does not need to create a new list to do so.

Upvotes: 3

Related Questions