gpt4 book ai didi

if-statement - 在 OCaml 中实现多个 if 语句

转载 作者:行者123 更新时间:2023-12-04 01:23:27 26 4
gpt4 key购买 nike

所以我对 OCaml 有点陌生,我试图找出一种方法让我的函数检查多个条件并在这些条件中的任何一个为真时修改变量

粗略的伪代码是

var list = []
if cond1 then 1::list
if cond2 then 2::list
etc

但是根据我的判断,一旦你输入一个 if 语句,你就会一直呆在它里面,直到它向函数返回一个值。有没有办法绕过这个限制?感谢您的时间,非常感谢提示或提示,因为我很想了解该语言

最佳答案

OCaml 变量是不可变的,你不能改变它们的值。所以你需要以不同的方式思考这个问题。一种合理的做法是让函数的值等于提供的列表,并在前面添加一些内容:

let f list =
if cond1 then 1 :: list
else if cond2 then 2 :: list
else 3 :: list

请注意 if在 OCaml 中是一个表达式,即它有一个值。它类似于 ?:受 C 语言影响的语言中的三元运算符。

这是一个 OCaml session ,显示了这样的函数。这只是一个例子,这不是一个有用的功能:
$ 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))

关于if-statement - 在 OCaml 中实现多个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22573021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com