F# Seq.head & Seq.tail type mismatch with custom types

前端 未结 2 1053
野性不改
野性不改 2021-01-21 12:36
type Suit = Spades | Clubs | Hearts | Diamonds
type Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
type Card = {suit: Su         


        
2条回答
  •  孤街浪徒
    2021-01-21 13:04

    You're passing cardValue the Seq.head function; you need to apply that function first and pass the result instead:

    let rec handValue (hand:Hand) =
        if Seq.length hand = 1
        then cardValue (Seq.head hand)
        else cardValue (Seq.head hand) + handValue (Seq.tail hand)
    

    N.b. this will fail if passed an empty sequence and isn't tail recursive; fixing these, along with a little redundancy removal, yields something like:

    let handValue hand =
        let rec impl acc h =
            if Seq.isEmpty h then acc
            else impl (cardValue (Seq.head h) + acc) (Seq.tail h)
        impl 0 hand
    

    That said, this is extremely inefficient; this code structure would work fine when using a list rather than a seq, but you're much better off using higher-order functions to process the latter:

    let handValue hand = hand |> Seq.sumBy cardValue
    

提交回复
热议问题