4

http://caml.inria.fr/pub/docs/manual-ocaml-400/manual021.html#toc79で与えられた例に関する有益なコメントをお待ちしております。

7.12 明示的な多相型注釈

type 'a t = Leaf of 'a | Node of ('a * 'a) t

let rec depth : 'a. 'a t -> 'b = function
|Leaf _ -> 1
| Node x -> 1 + depth x

この例の関数は理解できますが、タイプの「マップのような」関数を定義しようとすると

'a. 'a t -> ('a -> 'b) -> 'b t

例えば:

let rec tmap: 'a. 'a t ->(f:'a->'b) -> 'b t = function
|Leaf x ->  Leaf( f x) 
|Node x -> let res = tmap x in Node(res);;

次のエラーが表示されます。

Characters 67-77:
  |Leaf x ->  Leaf( f x)
              ^^^^^^^^^^

Error: This expression has type 'c t but an expression was expected of type
         (f:'a -> 'b) -> 'b t

私は完全に理解していません。有益なコメントをいただければ幸いです。

4

3 に答える 3

4

の周りに不適切に配置された括弧、ブランチ内の関数fへの引数を忘れた、および の量指定子を忘れたなど、いくつかの問題があります。最後に、PatJ の助けを借りて、次のように記述できます。tmapNode'b

type 'a t = Leaf of 'a | Node of ('a * 'a) t

let rec depth : 'a. 'a t -> 'b = function
  | Leaf _ -> 1
  | Node x -> 1 + depth x


let rec tmap: 'a 'b. 'a t -> f:('a -> 'b) -> 'b t =
  fun t ~f -> match t with
    | Leaf x -> Leaf (f x)
    | Node x ->
      Node (tmap ~f:(fun (x,y) -> f x, f y) x)

tmap (Node (Leaf (7,8))) ~f:(fun x -> x + 1, x + 2);;
- : (int * int) t = Node (Leaf ((8, 9), (9, 10)))
于 2015-02-17T23:01:17.630 に答える
0

大変お世話になりました。これで、テスト ケースが意図したとおりに動作します。

let int_tree = Node(Node(Leaf((3,-1),(0,4))));;
let char_tree = Node(Node(Leaf(('a','c'),('d','c'))));;

tmap int_tree ~f:(fun x -> x*x);;
- : int t = Node (Node (Leaf ((9, 1), (0, 16))))

tmap char_tree ~f:(fun x -> Char.uppercase x);;
- : char t = Node (Node (Leaf (('A', 'C'), ('D', 'C'))))

于 2015-02-19T20:39:56.377 に答える