作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要一个尾递归版本的 List.map
,所以我自己写的。这是:
let rec list_map f l ?(accum=[])=
match l with
head :: tail -> list_map f tail ~accum:(head :: accum)
| [] -> accum;;
File "main.ml", line 69, characters 29-31:
Warning X: this optional argument cannot be erased.
最佳答案
以前的解决方案确实可以编译,但不会给出预期的结果。函数f
永远不会应用于参数。正确的代码是:
let rec list_map f ?(accum = []) l = match l with
| head :: tail -> list_map f ~accum:(f head :: accum) tail
| [] -> accum;;
val list_map : ('a -> 'b) -> ?accum:'b list -> 'a list -> 'b list = <fun>
val list_map : 'a -> ?accum:'b list -> 'b list -> 'b list = <fun>
# list_map ( ( ** ) 2.) [1.;2.;3.;4.];;
- : float list = [16.; 8.; 4.; 2.]
# List.rev_map ( ( ** ) 2.) [1.;2.;3.;4.];;
- : float list = [16.; 8.; 4.; 2.]
let rec list_map f ?(accum = []) l = match l with
| head :: tail -> list_map f ~accum:(f head :: accum) tail
| [] -> List.rev accum;;
# list_map ( ( ** ) 2.) [1.;2.;3.;4.];;
- : float list = [2.; 4.; 8.; 16.]
关于ocaml - 可选参数无法删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1667232/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!