|> 运算符的作用与部分应用

role of the |> operator vs partial application

我有以下代码:

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 不对函数调用使用括号。在声明中

make_account (100) Deposit (50);;

你有两个不必要的分组括号,和

一样
make_account  100  Deposit  50 ;;

其中 make_account 应用了三个参数。你想写的是

make_account 100 (Deposit 50);;

相当于无括号

Deposit 50 |> make_account 100;;