OCaml 中的函数对书籍示例的混淆(初学者)
function upon function in OCaml Confusion about the books's example (beginner)
# let rec map1 f l = match l with
[]->[]
|h::t -> f h::map1 f t;;
val map1 : ('a -> 'b) -> 'a list -> 'b list = <fun>
我是 OCaml 新手,有两个问题:
- 第三行为什么
h :: map1 f t
前有个f? f 应该是 map1
函数中的参数。为什么书上的例子要分开来?
- 第一个例子
('a -> 'b) -> 'a list -> 'b list = <fun>
为什么会有b表?
书中解释说 b list 是函数 f
的结果,a list 是函数 f
的参数。但是,为什么下面的例子中没有a
、b
列表呢?它还有一个函数f
,它还在第三行单独放了f
。
# let rec apply f n x=
if n = 0 then x
else f ( apply f (n-1) x);;
val apply : ('a -> 'a) -> int -> 'a -> 'a = <fun>
|h::t -> f h::map1 f t
Ocaml语法的优先规则意味着上面的match子句被解析为
|h::t -> (f h)::(map1 f t)
当然 f h
是函数 f
对参数 h
的应用
换句话说,当列表 l
与模式 h::t
匹配时(因此 l
是头 h
和尾 t
的正确列表), 一对 made ::
(or built, or constructed) of head f h
and tail map1 f t
一个典型的用法是首先要有一个从整数到字符串的函数:
let nextasstr n = Printf.sprintf "(%d)" (n+1);;
所以 nextasstr 2
是不带引号的字符串 "(3)"
。当然 [2;3]
是一个整数列表,即 int list
然后map1 nextasstr [2;3]
被评估为[ "(3)"; "(4)" ]
,一个字符串列表,即string list
;您会看到第二个参数的类型与结果不同。 (这应该可以深入了解 'a list
与 'b list
的区别以及输入
map1 : ('a -> 'b) -> 'a list -> 'b list
),第一个参数是 任意 'a -> 'b
类型的函数
您应该会看到 Ocaml MOOC, follow the Ocaml tutorial, read its documentations。这可能需要数周的时间。
# let rec map1 f l = match l with
[]->[]
|h::t -> f h::map1 f t;;
val map1 : ('a -> 'b) -> 'a list -> 'b list = <fun>
我是 OCaml 新手,有两个问题:
- 第三行为什么
h :: map1 f t
前有个f? f 应该是map1
函数中的参数。为什么书上的例子要分开来? - 第一个例子
('a -> 'b) -> 'a list -> 'b list = <fun>
为什么会有b表? 书中解释说 b list 是函数f
的结果,a list 是函数f
的参数。但是,为什么下面的例子中没有a
、b
列表呢?它还有一个函数f
,它还在第三行单独放了f
。
# let rec apply f n x=
if n = 0 then x
else f ( apply f (n-1) x);;
val apply : ('a -> 'a) -> int -> 'a -> 'a = <fun>
|h::t -> f h::map1 f t
Ocaml语法的优先规则意味着上面的match子句被解析为
|h::t -> (f h)::(map1 f t)
当然 f h
是函数 f
对参数 h
换句话说,当列表 l
与模式 h::t
匹配时(因此 l
是头 h
和尾 t
的正确列表), 一对 made ::
(or built, or constructed) of head f h
and tail map1 f t
一个典型的用法是首先要有一个从整数到字符串的函数:
let nextasstr n = Printf.sprintf "(%d)" (n+1);;
所以 nextasstr 2
是不带引号的字符串 "(3)"
。当然 [2;3]
是一个整数列表,即 int list
然后map1 nextasstr [2;3]
被评估为[ "(3)"; "(4)" ]
,一个字符串列表,即string list
;您会看到第二个参数的类型与结果不同。 (这应该可以深入了解 'a list
与 'b list
的区别以及输入
map1 : ('a -> 'b) -> 'a list -> 'b list
),第一个参数是 任意 'a -> 'b
您应该会看到 Ocaml MOOC, follow the Ocaml tutorial, read its documentations。这可能需要数周的时间。