OCaml显式多态类型注释

时间:2015-02-17 22:45:12

标签: recursion polymorphism ocaml recursive-datastructures polymorphic-functions

我很乐意收到一些有用的评论,内容如下:
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

e.g:

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

我不完全明白。 我将不胜感激。

3 个答案:

答案 0 :(得分:3)

你有一些问题,比如在f周围放置不正确的括号,tmap分支中Node函数的遗忘参数,你忘了{{1}的量词}}。所以,最后,在PatJ的帮助下,我们可以写下以下内容:

'b

答案 1 :(得分:3)

你忘记了第二个论点。

let rec tmap:
 'a. 'a t ->(f:'a->'b) -> 'b t = (* asking for two arguments *)
 function (* takes only the first argument *)
|Leaf x -> Leaf( f x)
|Node x -> let res = tmap x in Node(res);; 

此外,'b也必须是多态的,因为只要你穿过树就想生成嵌套元组。

这应该是,感谢ivg:

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 -> let f (a,b) = (f a, f b) in Node ( tmap x ~f ) ;;

答案 2 :(得分:0)

非常感谢你的大力帮助。 现在,我的测试用例按预期工作:

let int_tree = Node(Node(Leaf((3,-1),(0,4))));;
让char_tree = 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 :(有趣的x - > Char.uppercase x);;
- :char t = Node(节点(Leaf(('A','C'),('D','C'))))

相关问题