如何更改列表中相同的所有元素?

时间:2013-03-10 12:32:44

标签: list functional-programming ocaml

如何在OCaml中替换列表中等于ct的所有元素?

我试过List.filter但没有成功:

List.fold_right (fun c -> t) (List.filter c myLst) []

List模块是否包含此任务的函数?

2 个答案:

答案 0 :(得分:3)

您可以使用map(请参阅List module):

open Printf;;

let l = ['a'; 'b'; 'c'; 'd'; 'c']
let l2 = List.map (fun x -> if (x = 'c') then 't' else x) l;;
List.iter (printf "%c ") l2;;

打印

a b t d t 

答案 1 :(得分:1)

如果您想使用List.fold_right,可以采用以下方法:

let replace lst = List.fold_right (fun elmt accum -> 
    let e = if elmt = 'c' then 't' else elmt in
    e::accum
) lst [];;
      val replace : char list -> char list = <fun>
# replace ['a'; 'b'; 'c'];;
- : char list = ['a'; 'b'; 't']

注意:不要在OCaml中使用==而不是=,它们有不同的含义。 ==测试物理相等,但=测试语义相等。因此,当您使用==时,即使两个值在语义上相等,它也可能返回false。

相关问题