所以我对OCaml有点新意,我试图找出一种方法让我的函数检查多个条件并修改变量,如果这些条件中的任何一个是真的
粗略的伪代码将是var list = []
if cond1 then 1::list
if cond2 then 2::list
etc
但是从输入if语句后我能够告诉你,只要它返回一个值给函数,你就会保留它。有没有解决这个限制的方法?感谢您的时间,提示或提示非常感谢,因为我很想理解语言
答案 0 :(得分:5)
OCaml变量是不可变的,你不能改变它们的值。所以你需要以不同的方式思考这个问题。一个合理的事情是拥有一个函数,其值等于提供的列表,并在前面添加了一些东西:
let f list =
if cond1 then 1 :: list
else if cond2 then 2 :: list
else 3 :: list
注意OCaml中的if
是一个表达式,即它有一个值。它类似于受C语言影响的?:
三元运算符。
这是一个OCaml会话,显示了这样的功能。这只是一个例子,这不是一个有用的功能:
$ ocaml
OCaml version 4.01.0
# let f list =
if List.length list > 3 then 1 :: list
else if List.length list > 1 then 2 :: list
else 3 :: list ;;
val f : int list -> int list = <fun>
# f [];;
- : int list = [3]
# f [1;2];;
- : int list = [2; 1; 2]
<强>更新强>
如果你想一直应用ifs代码如下:
let f list =
let list' = if cond1 then 1 :: list else list in
let list'' = if cond2 then 2 :: list' else list' in
let list''' = if cond3 then 3 :: list'' else list'' in
list'''
您可以在自己的函数中捕获重复的模式:
let f list =
let cpfx cond pfx l = if cond then pfx :: l else l in
cpfx cond3 3 (cpfx cond2 2 (cpfx cond1 1 list))
答案 1 :(得分:0)
如果您想要一系列if
语句,则每个if
必须返回unit
。您可以使用对列表的引用使其变为可变,在每个if
语句后面加分号并在结尾返回引用的列表:
let f list =
let list = ref list in
if cond1 then list := 1 :: !list;
if cond2 then list := 2 :: !list;
[...]
!list
;;
不会修改给定的列表,只有一个名为list
的新变量会影响函数定义中的原始变量。