具有未知值的函数有效。 OCaml的

时间:2013-12-11 09:42:52

标签: ocaml

我无法理解代码中的一些内容。它是OCaml中的程序,它从列表中的元素生成所有不同的对。这是我的代码:

let rec tmp f list x =
    match list with
    | [] -> x
    | h :: t -> f h (tmp f t x);;
    (*          ^ ^ (^        ) (1) *)

let rec distinctpairs lst = 
    match lst with
    | [] -> []
    | h :: t -> tmp ( fun x lt -> (h,x)::lt) t (distinctpairs t);;
    (*                    ^          ^ (2)                    *)
  1. 功能tmp会返回三个值吗?
  2. 当我不知道x是什么时,我怎么能给func辩论?
  3. 当我假设tmp返回三个值时,那就是为什么当我给tmp赋予( fun x lt -> (h,x)::lt)参数作为arg时,它是否有效?

1 个答案:

答案 0 :(得分:3)

<强> 1。函数tmp返回三个值吗?

let rec tmp f list x =
    match list with
    | [] -> x
    | h :: t -> f h (tmp f t x);;

这个问题的简单答案是没有

f h (tmp f t x)不是三个值,而是a function execution/application on f


<强> 2。当我不知道什么是x时,我怎么能给func一个参数?

let rec distinctpairs lst = 
    match lst with
    | [] -> []
    | h :: t -> tmp ( fun x lt -> (h,x)::lt) t (distinctpairs t);;

这里的真相是you know x。 x被定义为匿名函数fun x lt -> (h, x)::lt的参数。


当我假设tmp返回三个值时,那就是为什么当我给tmp作为arg(有趣的x lt - &gt;(h,x):: lt)参数时,它有效吗?

首先,当ocaml看到tmp f list x时,ocaml除了tmp accepts 3 parameters之外什么都不知道。

当ocaml到达| [] -> x时,它知道x是什么类型,tmp will return the same type as x

当ocaml到达| h::t -> f h (tmp f t x)时,它知道f必须是一个函数并且f will have 2 parameters: one with type of h and one with type of x

然后在distinctpairs函数中,( fun x lt -> (h,x)::lt)是一个匿名函数,它与上面的预测完全匹配。


编写这两个函数的更好方法:

let rec tmp f x = function
    | [] -> []
    | h :: t -> f h (tmp f x t)

let rec distinctpairs = function
    | [] -> []
    | h :: t -> tmp (fun x lt -> (h,x)::lt) (distinctpairs t) t

我还建议你阅读Real World Ocaml本书。这是关于OCaml的最新,最全面的书,很好。

当您尝试进入函数式编程世界时,没有捷径。这不像你学习西班牙语作为英语演讲者。这更像是学习中文/日文作为英语使用者。

整个想法与Java或C#或C完全不同,当然,比Java(我的个人感觉)要好得多。所以我建议你从地面学习。

相关问题