gpt4 book ai didi

Ocaml 中的 List.Fold_Left 类型系统?

转载 作者:行者123 更新时间:2023-12-02 06:38:27 25 4
gpt4 key购买 nike

编写一个 Ocaml 函数 list_print : string list -> unit 从左到右打印列表中的所有字符串:

假设我有一个 Ocaml 函数 list_print: string list -> unit 从左开始打印列表中的所有字符串以写入。现在正确的解决方案是:

let list_print lst = List.fold_left (fun ( ) -> fun s -> print_string s) () lst;;

但是在写我的解决方案时,我是这样写的:

let list_print lst = List.fold_left (fun s -> print_string s) () lst;;

但这给了我

错误:此表达式的类型为 unit 但表达式应为 'a -> string

为什么我需要第一个参数 fun() -> 在 fun 之前?我对 Ocaml 还是个新手,所以这个类型系统让我很困惑

最佳答案

fold_left(和fold_right)的目的是在进行过程中积累一个值。额外的参数就是这个累加值。

您可以使用 List.iter 来解决您的问题。它积累值(value)。

您可以将 List.iter 视为 List.fold_left 的一个版本,它累积类型为 unit 的值。而且,事实上,您可以这样实现它:

let iter f = List.fold_left (fun () a -> f a) ()

要点(与 unit 一样)是该类型只有一个值,因此它表示该值不感兴趣的情况。

关于Ocaml 中的 List.Fold_Left 类型系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com