11

数字の文字列が与えられた場合、ゼロ以外の文字を文字列内の位置にマッピングする一連のタプルが必要です。例:

IN: "000140201"
OUT: { (3, '1'); (4, '4'); (6, '2'); (8, '1') }

解決:

let tuples = source
             |> Seq.mapi (fun i -> fun c -> (i, c))
             |> Seq.filter (snd >> (<>) '0')

このような(fun i -> fun c -> (i, c))単純でおそらく一般的な操作では、本来よりもはるかに多くのタイピングが行われているようです。必要な関数を宣言するのは簡単です:

let makeTuple a b = (a, b)
let tuples2 = source
              |> Seq.mapi makeTuple
              |> Seq.filter (snd >> (<>) '0')

But it seems to me that if the library provides the snd function, it should also provide the makeTuple function (and probably with a shorter name), or at least it should be relatively easy to compose. I couldn't find it; am I missing something? I tried to build something with the framework's Tuple.Create, but I couldn't figure out how to get anything other than the single-argument overload.

4

2 に答える 2

11

しかし、ライブラリが snd 関数を提供する場合、makeTuple 関数も提供する必要があるように思えます。

F# は、タプルを構成するよりも頻繁に ( , を使用して)fstタプルを分解することを前提としています。snd機能ライブラリの設計は、多くの場合、最小限の原則に従います。一般的なユースケースの関数を提供するだけで、他の関数は簡単に定義できるはずです。

見つかりませんでした。私は何かを逃していますか?

いいえ、そうではありません。これは、 FSharpPlustuple2が、などを定義したのと同じ理由です。以下に、 Operatorstuple3から直接ユーティリティ関数を示します。

/// Creates a pair
let inline tuple2 a b = a,b
/// Creates a 3-tuple
let inline tuple3 a b c = a,b,c
/// Creates a 4-tuple
let inline tuple4 a b c d = a,b,c,d
/// Creates a 5-tuple
let inline tuple5 a b c d e = a,b,c,d,e
/// Creates a 6-tuple
let inline tuple6 a b c d e f = a,b,c,d,e,f

フレームワークの Tuple.Create で何かを構築しようとしましたが、単一引数のオーバーロード以外のものを取得する方法がわかりませんでした。

F# コンパイラはSystem.Tuple<'T1, 'T2>、タプルにパターン マッチング イディオムを適用するために のプロパティを非表示にします。詳細については、F# タプルの拡張メソッドを参照してください。

とはいえ、F# ではポイントフリー スタイルが常に推奨されるわけではありません。ポイントフリーが好きなら、自分で少し重い物を持ち上げる必要があります。

于 2013-02-09T08:01:21.883 に答える