如何创建函数集合?

How do I create a collection of functions?

我只想说 "usd_to_euro 100" 并为我的特定日期取回正确数量的欧元(例如:90)。 create_exchange_functions 需要 return 什么?

let create_exchange_functions (usd_to_euro_rate, usd_to_yuan_rate, usd_to_peso_rate, usd_to_pound_rate, usd_to_ruble_rate) = 
    (??, ??, ??, ....??);

//x日上午我运行这个:

let (usd_to_euro, usd_to_yuan, usd_to_peso, usd_to_pound, usd_to_ruble) = create_exchange_functions(0.9, 4., 3., 0.6, 5.);
usd_to_pound 10.;

//第 y 天早上我 运行 这个:

let (usd_to_euro, usd_to_yuan, usd_to_peso, usd_to_pound, usd_to_ruble) = create_exchange_functions(0.92, 3.8, 3., 0.65, 5.);
usd_to_pound 10.;

//第z天早上我运行这个:

let (usd_to_euro, usd_to_yuan, usd_to_peso, usd_to_pound, usd_to_ruble) = create_exchange_functions(0.92, 3.8, 3., 0.62, 5.);
usd_to_pound 10.;

给定

let create_exchange_functions (usd_to_euro_rate, usd_to_yuan_rate, usd_to_peso_rate, usd_to_pound_rate, usd_to_ruble_rate) = 
(??, ??, ??, ....??);

如何进行这项工作。

让我们先简化一个项目,然后我们将完成所有项目。

let create_exchange_functions usd_to_euro_rate = 
    let toEuro dollar = usd_to_euro_rate * dollar
    toEuro

理解您想要什么的关键是您想要一个 returns 具有 curried 值的新函数的函数。专门针对此示例,curried 参数是函数需要但在创建函数时未给出的参数。

要查看此内容,请将类型添加到 create_exchange_functions

let create_exchange_functions (usd_to_euro_rate : float) : (float -> float) = 
    let toEuro dollar = usd_to_euro_rate * dollar
   toEuro

我们看到 create_exchange_functions 接受一个值 usd_to_euro_rate 和 returns 一个函数 (float -> float) 这就是我们想要的。

但是请注意,当我们创建函数 toEuro 时,我们只给了它 usd_to_euro_rate 的值,而不是 dollar 的值。这就是柯里化正在做的事情。它允许我们创建需要参数的函数,然后可以提供参数。那么让我们看看这是如何完成的。

首先使用 create_exchange_functions

创建函数 usd_to_eruo
let usd_to_euro = create_exchange_functions 0.9

注意usd_to_euro的签名是

val usd_to_euro : (float -> float)

所以如果我们给它一个浮点值,它会返回另一个浮点值。 我们给它的价值是美元的价值

let dollar = 10.0

我们像

一样使用它
let euro = usd_to_euro dollar
printfn "Dollar: %A to Euro: %A" dollar euro

这给出

Dollar: 10.0 to Euro: 9.0

这就是我们想要的。

现在对所有汇率执行此操作

let create_exchange_functions (usd_to_euro_rate, usd_to_yuan_rate, usd_to_peso_rate, usd_to_pound_rate, usd_to_ruble_rate) = 
    let toEuro dollar = usd_to_euro_rate * dollar
    let toYuan dollar = usd_to_yuan_rate * dollar
    let toPeso dollar = usd_to_peso_rate * dollar
    let toPound dollar = usd_to_pound_rate * dollar
    let toRuble dollar = usd_to_ruble_rate * dollar
    (toEuro, toYuan, toPeso, toPound, toRuble)

let (usd_to_euro, usd_to_yuan, usd_to_peso, usd_to_pound, usd_to_ruble) = 
    create_exchange_functions(0.9, 4., 3., 0.6, 5.)

let dollar = 10.0
let pound = usd_to_pound dollar
printfn "Monday - Dollar: %A to Pound: %A" dollar pound

Monday - Dollar: 10.0 to Pound: 6.0

let (usd_to_euro, usd_to_yuan, usd_to_peso, usd_to_pound, usd_to_ruble) = 
    create_exchange_functions(0.92, 3.8, 3., 0.65, 5.)

let pound = usd_to_pound dollar
printfn "Tuesday - Dollar: %A to Pound: %A" dollar pound

Tuesday - Dollar: 10.0 to Pound: 6.5