【问题标题】:OCaml type mismatch during compilation编译期间 OCaml 类型不匹配
【发布时间】:2013-10-27 21:48:28
【问题描述】:

看看我的代码:

let my lst p q =
  if lst = [] then
    []
  else
    let i = 0 in let res = [] in let acc=[] in
    fold_left ( fun acc h -> 
      if (not (p h) && not(q h)) then
    ((i+1), [], res)
      else if (p h && not (q h)) then
    ((i+1), (i::acc),res)
      else if (not (p h) &&  q h) then
    ((i+1), [] (acc@res))
      else
    ((i+1), [], ((i::acc)@res))) 
     (i,acc,res) lst;;

我得到了编译错误:

这个表达式的类型为 int * int list * 'a list 但是需要一个 int list 类型的表达式

你能帮帮我吗?

【问题讨论】:

  • 编译错误是指哪一行?
  • ((i+1), (i::acc),res)
  • 我猜这里有一个错字(i+1), [] (acc@res)) 缺少逗号

标签: ocaml fold type-mismatch


【解决方案1】:

问题来自您使用折叠功能的方式。

fold_left ( fun acc h -> 
  ...
)  

关于你的累加器,这是一个三元组最好如下,

 ....
fold_left ( fun (i', acc', res') h -> 
  here replace i, acc res by i' acc' res'
)  

进一步去掉i、acc、res的定义。
直接把他们的价值观这样,

 ....
fold_left ( fun (i', acc', res') h -> 
  here replace i, acc res by i' acc' res'
)  (0, [], []) lst;;

最后fold_left的匿名函数调用,应该绑定到fold的调用之上。

.....
let helper (i, acc, res) x = 
    .....
in fold_left helper (0, [], []) lst;;

【讨论】:

  • np,最后一点,尝试评估let lst = [] in List.fold_left (fun a x -> a*100 + x) 1 lst
猜你喜欢
  • 2019-03-27
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多