Cod*_*nja 3 recursion ocaml if-statement
所以我对OCaml有点新意,我试图找出一种方法让我的函数检查多个条件并修改变量,如果这些条件中的任何一个为真
粗糙的伪代码会
var list = []
if cond1 then 1::list
if cond2 then 2::list
etc
Run Code Online (Sandbox Code Playgroud)
但是,一旦你输入if语句,我就可以告诉你,只要它返回一个值给函数,你就会保留它.有没有解决这个限制的方法?感谢您的时间,提示或提示非常感谢,因为我很想理解这门语言
OCaml变量是不可变的,你不能改变它们的值.所以你需要以不同的方式思考这个问题.一个合理的事情是拥有一个函数,其值等于提供的列表,并在前面添加了一些东西:
let f list =
if cond1 then 1 :: list
else if cond2 then 2 :: list
else 3 :: list
Run Code Online (Sandbox Code Playgroud)
注意,if
在OCaml中是表达式,即它具有值.它类似于?:
受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]
Run Code Online (Sandbox Code Playgroud)
更新
如果你想一直应用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'''
Run Code Online (Sandbox Code Playgroud)
您可以在自己的函数中捕获重复的模式:
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))
Run Code Online (Sandbox Code Playgroud)