我正在尝试创建一个接受可变参数的函数,但我似乎无法为F#找到任何可行的解决方案。
let expression = (fun a b -> a || b)
let expressionTriple = (fun a b c -> (a || b) && c)
// This doesn't work because expression can either be a function that takes fixed arguments
let truthTable numPredicates expression =
if numPredicates = 2 then
expression true true
else
expression true true false
truthTable 2 expression
truthTable 3 expressionTriple如何将可变数量的参数传递到表达式函数中?
发布于 2017-11-16 18:27:55
在F#中,具有不同签名(包括不同数量的参数)的函数被认为是不同的类型。而且,当您想让一个函数接受一个参数时,它可能是两种不同的类型(甚至是十几种不同的类型),您需要使用受歧视的工会。下面是如何以编译和执行您想要做的事情来编写代码的方法:
type Expression<'a> =
| Double of ('a -> 'a -> 'a)
| Triple of ('a -> 'a -> 'a -> 'a)
let expression = fun a b -> a || b
let expressionTriple = fun a b c -> (a || b) && c
// This works because expression is a discriminated union
let truthTable expression =
match expression with
| Double f -> f true true
| Triple f -> f true true false
truthTable (Double expression)
truthTable (Triple expressionTriple)如果您想要添加一个四参数版本,只需向受歧视的联合添加一个Quad of ('a -> 'a -> 'a -> 'a -> 'a)大小写,依此类推。
如果您对此有任何疑问,比如我为什么用泛型类型'a而不是bool来编写这篇文章,请随时询问后续问题。
发布于 2017-11-17 17:32:59
let expression = (fun [a; b] -> a || b)
let expressionTriple = (fun [a; b; c] -> (a || b) && c)
let truthTable numPredicates expression =
if numPredicates = 2 then
expression [true; true]
else
expression [true; true; false]
truthTable 2 expression
truthTable 3 expressionTriple https://stackoverflow.com/questions/47335279
复制相似问题