Ocaml - wrong type

我与影子孤独终老i 提交于 2019-12-11 16:58:09

问题


I want check if tree is balanced (It means that each leaf is on the same depth) but I have problem with wrong type.

type 'a tree = Node of 'a * 'a tree list;;

let rec fold_tree f (Node (x,l)) =
f x (map (fold_tree f) l);;

let is_balanced t =
  fst(
    fold_tree 
      (fun _ (l: (bool * int) list ) ->  
        ((fold_left
           (fun h (flag,first_value)-> 
             ((fst h)=first_value)&&flag,first_value)
           (true,snd(hd l) ) 
           l))
       )
   t);;

The problem is there:

((fold_left(fun h (flag,first_value)-> ((fst h)=first_value)&&flag,first_value) (true,snd(hd l) ) l))

Ocaml tells me that this is type of bool * bool but I am convinced that this is type of bool * int because l is type of (bool * int) list so hd l is type of (bool * int) so snd(hd l) is type of int...


回答1:


Some pieces of advice:

  • Name your intermediary functions
  • Avoid opening List
  • Avoid using List.hd (in order properly handle the empty list case)
  • Believe the typechecker
  • Use type annotations when debugging with the typechecker help

In your case, you should have a look at the type of your inner function

fun (h:'a) (flag,first_value): 'a-> 
  (fst h=first_value) && flag,first_value


来源:https://stackoverflow.com/questions/53262311/ocaml-wrong-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!