4

F# のどこかに複数インスタンス パターンはありますか?

私がリストに取り組んでいると考えてください。私は次のパターンマッチングを持っています

match l with
| [] | [_] -> l  //if the list is empty or contains only one item, simply return it
|        

    //is there a pattern to test if all of the elements are identical?

言い換えれば、[] または [1] を渡すと単純にリストが返され、[1;1;1;...] が返されますが、その最後のパターンにパターン マッチする方法がわかりません。これは可能ですか?または、私が使用できるより良いアプローチがありますか? 繰り返しパターンについてはどこにも見つかりませんでした。

4

3 に答える 3

8

あなたが望むことをするパターンは知りませんが、これを行うことができます:

let allSame L =
    match L with
    | [] | [_] -> L
    | h::t when t |> List.forall ((=) h) -> L
    | _ -> failwith "unpossible!" //handle the failing match here

PSあなたはシーケンスについて話しているが、あなたの一致はあなたがリストを扱っていることを示している. シーケンスに対応するコードは次のようになります

let allSameSeq s = 
    match Seq.length s with
    | 0 | 1 -> s
    | _ when Seq.skip 1 s |> Seq.forall ((=) (Seq.head s)) -> s
    | _ -> failwith "unpossible!"

この関数のパフォーマンスは、リストベースの関数よりも悪い可能性があることに注意してください。

于 2009-10-29T11:10:48.333 に答える
4

これは、マルチケースのアクティブ パターンを使用したソリューションです。

let (|SingleOrEmpty|AllIdentical|Neither|) (lst:'a list) =
    if lst.Length < 2 then
        SingleOrEmpty
    elif List.forall (fun elem -> elem = lst.[0]) lst then
        AllIdentical
    else
        Neither

let allElementsIdentical lst:'a list =
    match lst with
    |SingleOrEmpty|AllIdentical -> lst
    |Neither -> failwith "Not a suitable list"
于 2009-11-01T03:40:50.433 に答える
2

次のいずれかを検討します。


yourSequence |> Seq.windowed(2) |> Seq.forall(fun arr -> arr.[0] = arr.[1])

また


let h = Seq.hd yourSequence
yourSequence |> Seq.forall((=) h)

可能な場合はライブラリ関数を使用することをお勧めします;)

于 2009-10-31T12:06:15.647 に答える