0

海図で深度曲線を表すために F# で構造体を作成しようとしています。座標のリストと、表現される深さを示すフロートを含める必要があります (例: "4.5 メートル")。私はこのようにしました:

type Coord =
    struct
        val X : float
        val Y : float
        new(x,y) = { X = x ; Y = y }
    end

type DepthCurve =
    struct
        val Coords : list<Coord>
        val Depth  : float
        new(list_of_Coords, depth) = { Coords = list_of_Coords ; Depth = depth}
    end

let myCoord1 = new Coord(1.,2.)
let myCoord2 = new Coord(3.,4.)
let myDepthCurve = new DepthCurve([myCoord1;myCoord2] , 5. )

私の問題は、次のように、ポリゴンとその座標を一度に作成できないことです。

let myDepthCurve = {coords=[[1.;2.];[3.;4.]] , 5}

これには解決策があります:

type Coord  = { X : float; Y : float }
type 'a DepthCurve = {coords: 'a list;}
let myDepthCurve = {coords=[[1.;2.];[3.;4.]]};;

しかし、構造体に深さを示すフロートを持たせることも、リストの型を Coords だけに制限することもできません。

両方の長所をどのように組み合わせますか?

4

2 に答える 2

1

作成したオブジェクト型は、コンストラクターを持つ標準の .NET 構造です。特別な F# レコード初期化構文 ( ) はありません{ ... }

あなたの問題のために、小さなラッパー関数を書くことができます:

let curve depth coords = New DepthCurve([for (x, y) in coords -> New Coord(x, y)], depth)

このように使用

let testCurve = curve 10. [(1., 2.); (3., 4.); ...]

短縮されたレコード構文で構造を宣言するときは、次のようにする必要があります。

type Coord = float * float // Type-alias for a 2D-float-tuple
type DepthCurve = { coords : Coord list; depth : float }

let myCurve = { coords = [(1., 2.); ...], depth = 42. }

一般的なリストを使用する理由はありません。指定するだけですCoord list(意味List of Coords)。[1; 2; 3]また、リスト ( ) とタプル ( )の違いに注意してください(1, 2, 3)。後者は、座標を表すのにより適しています。

F# の構造と型に関するこの記事をご覧ください。

于 2009-07-24T10:47:16.327 に答える
0

答えは、プログラムの作成方法によって異なります。

関数型パラダイム (突然変異なし、高次関数、パターン マッチングなし) を積極的に使用する場合、私は 3 つの選択肢に投票します。

(* tuple with type constractor and any getters you need: *)
let makeCoord x y = (x,y)
let makeCurve depth coords = (depth,coords)
let addCurveCoord (depth,coords) coord = (depth, coord::coords)
let getCurveDepth (depth,_) = depth
let getCurveCoords (_,coords) = coords
let getFirstCurveCoord (_,coords) = List.hd coords
//...

(* or types described by Dario *)
(* or tagged unions for case you need specific access to parts of your data *)

OOP を好む場合は、単純なオブジェクト階層を作成できます。

FP の主な利点は、プログラム構築のどの段階でも簡単に設計を変更できることです。しかしもちろん、明示的な状態引数によってコストがかかります。しかし、モナド式でそれらを打ち負かすかもしれません:)

于 2009-07-24T13:27:52.317 に答える