List 如何将函数仅映射到列表中的某些元素?
例如,如果您有一个函数List 如何将函数仅映射到列表中的某些元素?,list,map,if-statement,functional-programming,ocaml,List,Map,If Statement,Functional Programming,Ocaml,例如,如果您有一个函数(funx->x+1),并且希望将其映射到[1;2;3]。但是,您只希望在x=1时映射它,这样输出就是[2;2;3]。你是怎么做到的 使用OCaml,我尝试: let rec foo (input : int list) : int list = match input with | [] -> [] | hd::tl -> List.map (fun x -> if x=1 then (x+1)) input;; 我尝试了“when”语
(funx->x+1)
,并且希望将其映射到[1;2;3]
。但是,您只希望在x=1
时映射它,这样输出就是[2;2;3]
。你是怎么做到的
使用OCaml,我尝试:
let rec foo (input : int list) : int list =
match input with
| [] -> []
| hd::tl -> List.map (fun x -> if x=1 then (x+1)) input;;
我尝试了“when”语句,但没有效果。此处缺少
else
分支
你快到了。您只需要做一个完整的if/else语句:
如果x=1,则(x+1)否则x
OCaml要求在上述表达式的任何分支上都有一个返回值
需要明确的是,when
保护在这里是不相关的,因为它用于条件模式匹配。由于模式匹配在这种情况下是多余的,因此您的功能可能会缩短很多:
let foo input =
List.map (fun x -> if x=1 then x+1 else x) input
您实际上可以使用
when
语句,即使我更喜欢@pad的解决方案:
let foo (input : int list) : int list =
let rec aux acc input =
match input with
[] -> List.rev acc
| x :: xs when x = 1 -> aux ((x + 1) :: acc) xs
| x :: xs -> aux (x :: acc) xs
in
aux [] input
我觉得我试过了,但没用,但刚刚奏效了。摇滚明星,你。感谢您提供有关“何时”的提示。这是一个尾部递归;-)是的,它是尾部递归的,但我更喜欢使用List.map:-)的解决方案