活动模式 - 连续元素的检查列表

时间:2017-11-28 16:35:05

标签: f# functional-programming f#-interactive

因此,作为一项学校作业,我必须编写一个识别扑克牌的部分主动模式,例如:

let (|FullHouse|_|) (x: (string * string) list) =
    x
    |> List.groupBy snd
    |> List.sortByDescending fst
    |> List.forall (fun (_, v) -> v |> List.length > 1)
    |> function true -> Some () | _ -> None

let x6 =
    match [("S", "2"); ("S", "2"); ("S", "Q"); ("S", "Q"); ("S", "Q")] with
    | FullHouse -> sprintf "Full house"
    | _ -> "Nothing"

我已经成功完成9手中的6手,但我无法弄清楚如何检查手中是否有直线(5个值是连续的,例如,3,4,5,6, 7)。有没有清单。操作员可以帮我这么做吗?

1 个答案:

答案 0 :(得分:2)

在评论的帮助下,我设法解决了这个问题,我在这里为其他有相同(或类似)问题的人发布解决方案。

let GiveValue (x: string) =
    match x with
    | "2" -> 2
    | "3" -> 3
    | "4" -> 4
    | "5" -> 5
    | "6" -> 6
    | "7" -> 7
    | "8" -> 8
    | "9" -> 9
    | "10" -> 10
    | "J" -> 11
    | "Q" -> 12
    | "K" -> 13
    | "A" -> 14
    | _ -> 0

let (|Straight|_|) (x: (string * string) list) =
    x
    |> List.map (fun (_, v) -> v)
    |> List.map GiveValue
    |> List.sort
    |> List.pairwise
    |> List.forall (fun (x, y) -> y-x = 1)
    |> function true -> Some () | _ -> None

let x4 =
    match [("S", "J"); ("D", "9"); ("S", "8"); ("S", "10"); ("S", "Q")] with
    | Straight -> sprintf "Straight"
    | _ -> "Nothing"