在 gleam 中编写控制流代码的正确方法[关闭]

问题描述 投票:0回答:1

考虑以下伪代码

fn test_function(arg) {
   if check_first_cond(arg)  { return transform_first(arg) }
   if check_second_cond(arg) { return transform_second(arg) }
   if check_third_cond(arg)  { return transform_third(arg) }
   return transform_default(arg)
}

gleam
中编写上述代码的一些方法是:

fn test_function1(arg) {
    case check_first_cond(arg) {
       True -> transform_first(arg)
       False -> case check_second_cond(arg) {
                    True -> transform_second(arg)
                    False -> case check_third_cond(arg) {
                                 True -> transform_third(arg)
                                 False -> transform_default(arg)
                             }
                }
     }
}
// Or
fn test_function2(arg) {
    let c1 = check_first_cond(arg)
    let c2 = check_second_cond(arg)
    let c3 = check_third_cond(arg)

    case c1, c2, c3 {
        True, _, _         -> transform_first(arg)
        False, True, _     -> transform_second(arg)
        False, False, True -> transform_third(arg)
        _, _, _            -> transform_default(arg)
    }
}

如何以正确/更漂亮的方式编写此类代码?

有没有一种闪光/功能惯用的方式来编写这样的代码?

我相信这一点,函数末尾只有一个返回表达式。我正在阅读有关

gleam

use
的内容,但无法正确理解它们。谢谢,非常感谢任何帮助。
    

functional-programming gleam gleamlang
1个回答
0
投票
bool.guard

use
来使用它,如下所示:
bool.guard

根据
docs

,上面的代码翻译为import gleam/bool fn test_function3(arg) { use <- bool.guard(check_first_cond(arg), transform_first(arg)) use <- bool.guard(check_second_cond(arg), transform_second(arg)) use <- bool.guard(check_third_cond(arg), transform_third(arg)) transform_default(arg) }

这里的关键思想是:

    test_function1
  • 右侧需要是省略最后一个参数的函数调用。
    最后一个参数是函数类型,即它将用作回调,回调的主体将是
  • <-
  • 之后块中的其余代码。
    回调可以有参数,这些参数定义在 
  • use
  • 的左侧(在这种情况下没有参数)
    
        
© www.soinside.com 2019 - 2024. All rights reserved.