【问题标题】:role of the |> operator vs partial application|> 运算符与部分应用程序的作用
【发布时间】:2020-03-25 18:39:03
【问题描述】:

我有以下代码:

type transaction = Withdraw of int | Deposit of int | Checkbalance

(* Bank account generator. *)
let make_account(opening_balance: int) =
    let balance = ref opening_balance in
    fun (t: transaction) ->
      match t with
        | Withdraw(m) ->  if (!balance > m)
                          then
                            ((balance := !balance - m);
                            (Printf.printf "Balance is %i" !balance))
                          else
                            print_string "Insufficient funds."
        | Deposit(m) ->
           ((balance := !balance + m);
            (Printf.printf "Balance is %i\n" !balance)) 
        | Checkbalance -> (Printf.printf "Balance is %i\n" !balance)
;;

每当我尝试运行以下命令时:make_account(100) Deposit(50) ;; 我收到以下错误:此函数的类型为 int -> transaction -> unit。它适用于太多的论点;也许你忘记了一个 `;'。

但是以下命令可以正常工作Deposit(50) |> make_account(100) ;;

但是为什么这两行代码不等效呢? (make_account 100) 不应该替换为 (fun (t: transaction) -> ...) 吗?因为那时我不明白为什么我的第一次尝试没有奏效。

谢谢!

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    请注意,Ocaml 不使用括号进行函数调用。在声明中

    make_account (100) Deposit (50);;
    

    你有两个不必要的分组括号,它是一样的

    make_account  100  Deposit  50 ;;
    

    make_account 与三个参数一起应用。你想写的是

    make_account 100 (Deposit 50);;
    

    相当于无括号

    Deposit 50 |> make_account 100;;
    

    【讨论】:

    • 绝对!谢谢你。那么 (Deposit 50) 周围的 () 的作用是将其分组为一个单独的表达式,以便 ocaml 可以将其解释为 make account 返回的函数的参数对吗?
    • @JosephhansBouAssaf 是的,没错。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多