How can I select the first set of elements within a list?

How can I select the first set of elements within a list via index?

I am trying to think functional even though the code below is somewhat imperative when attempting to retrieve the first two cards.

let deal (deck: Card list) =
// ------------------------------------
//  let card1 = deck |> Seq.item 0 // Rewrite this logic of getting first two cards
//  let card2 = deck |> Seq.item 1
// ------------------------------------
    let hand = [<get first two elements in deck>]
    let deckUsed = deck |> Seq.except [card1; card2;]
    (card1, card2, deckUsed);;

Answers


How about something like this?

let deal =
    function
    |card1::card2::deckUsed -> Some (card1, card2), deckUsed
    |_ -> None, []

You can retrieve the results:

let hand, newDeck = deal deck
    match hand with
    |Some (card1, card2) -> // do something with the cards
    |None -> // do something if no cards

I've just used a simple option type but you might want to use a more descriptive union case to handle dealing from a deck with cards available and trying to deal from an empty deck.

Edit: I took the deck list out of the option type because you can always map an empty deck back to an empty deck, that could potentially be handy in certain use cases.


You could use pattern matching:

let card1 :: card2 :: unused = deck

Note that this fails for decks with less than two cards, as does indexing.


Need Your Help

Jenkins configuration: can't see "MSBuild SonarQube Runner" section

jenkins sonarqube-msbuild-runner

I can see this part in my local installed Jenkins server, but can't find it in my company's Jenkins servers. What's missing to make it show? The SonarQube Runner and Sonar sections are there.