gpt4 book ai didi

javascript - 任意类型的函数调用

转载 作者:行者123 更新时间:2023-12-02 08:08:49 25 4
gpt4 key购买 nike

我正在尝试实现一个函数 f 以便在调用时如下所示:

(((f 1) 2) 3) ()

它返回 1、2 和 3 的总和,即 6。只有当使用 Unit 参数 () 调用它时,计算才会发生并返回总和。

例如,在 Javascript (ES6) 中,它可以这样实现:

let f = (v, acc = 0) => {
if (typeof v === 'undefined') return acc;
return next => f(next, acc + v);
};

f(1)(2)(3)(); // 6

然而,在具有强类型的 Ocaml 中,它并不那么清晰,或者至少不那么简洁。

编辑:这是我使用变体类型的尝试:

type any =
| Nothing
| Number of int

type result =
| Int of int
| Fn of (any -> result)


let rec sumfun ?(acc=0) v =
match v with
| Nothing -> Int(acc)
| Number n -> Fn(fun next -> sumfun ~acc:(acc+n) next)

let _ =
let a = sumfun (Number 2) in
match a with
| Int n -> print_int n
| Fn f ->
let b = f (Number 3) in
match b with
| Int n -> print_int n
| Fn f ->
let c = f Nothing in
match c with
| Int n -> print_int n
| Fn f -> ()

因为对 sumfun 的调用非常复杂。有没有比这更好、更简洁或更惯用的方式?

最佳答案

正如评论中所指出的,一般建议是不要做这样的事情。您的特定示例自然会用列表表示:

let sum = List.fold_left (+) 0

let n = sum [1; 2; 3]

无论类型如何,我都看不到使用您展示的复杂结构有任何优势。

但无论如何要回答您最初的问题,您能做的最好的可能就是为应用程序提供自定义运算符,例如

let ($) f x = match f (Number x) with Fn f' -> f' | _ -> assert false
let ($$) f () = match f Nothing with Int n -> n | _ -> assert false

let n = sumfun $ 1 $ 2 $ 3 $$ ()

(我尝试使用 GADT 来避免那里的 assert false,但显然它们与可选参数的交互很糟糕。)

但要重申一点:不要。

关于javascript - 任意类型的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48959741/

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