我正在寻找一种将此列表简化为布尔值的方法。这是原文:
let ones = [1;1;1;1]
let twos = [2;2;2;2]
let bad = [1;2;3]
let isAllOnes = List.forall (fun op -> op = 1)
let isAllTwos = List.forall (fun op -> op = 2)
let isOneOrTwo ops = isAllOnes ops || isAllTwos ops
isOneOrTwo ones |> should be True
isOneOrTwo twos |> should be True
isOneOrTwo bad |> should be False
我正在尝试使用一种reduce来重构它。像这样:
let isOneOrTwo ops = [isAllOnes; isAllTwos] |> List.tryFind (fun acc -> acc ops)
(isOneOrTwo ones).IsSome |> should be True
(isOneOrTwo twos).IsSome |> should be True
(isOneOrTwo bad).IsSome |> should be False
我不喜欢 isOneOrTwo 如何简化为一个选项。我真的很想将列表简化为布尔值,以便我的断言看起来像这样:
isOneOrTwo ones |> should be True
isOneOrTwo twos |> should be True
isOneOrTwo bad |> should be False
有人知道如何做到这一点吗?List.reduce不起作用,因为类型不同。
将 List.tryFind 替换为 List.exists
let ones = [1;1;1;1]
let twos = [2;2;2;2]
let bad = [1;2;3]
let allOnes = List.forall ((=) 1)
let allTwos = List.forall ((=) 2)
let isOneOrTwo l = [allOnes; allTwos] |> List.exists (fun f -> f l)
printfn "%A " (isOneOrTwo ones) // true
printfn "%A " (isOneOrTwo twos) // true
printfn "%A " (isOneOrTwo bad) // false