F#将带有参数的运算符传递给函数 [英] F# passing an operator with arguments to a function
问题描述
您能否仅使用部分应用的运算符传递除以2"或减1"之类的运算,其中加1"如下所示:
Can you pass in an operation like "divide by 2" or "subtract 1" using just a partially applied operator, where "add 1" looks like this:
List.map ((+) 1) [1..5];; //equals [2..6]
// instead of having to write: List.map (fun x-> x+1) [1..5]
正在发生的是将1作为第一个参数应用到(+),并将列表项作为第二个参数应用.对于加法和乘法,此参数顺序无关紧要.
What's happening is 1 is being applied to (+) as it's first argument, and the list item is being applied as the second argument. For addition and multiplication, this argument ordering doesn't matter.
假设我想从每个元素中减去1(这可能是一个常见的初学者错误):
Suppose I want to subtract 1 from every element (this will probably be a common beginners mistake):
List.map ((-) 1) [1..5];; //equals [0 .. -4], the opposite of what we wanted
1作为第一个参数应用于(-),所以我得到的是(1 - list_item)
而不是(list_item - 1)
.我可以将其重写为添加负数而不是减去正数:
1 is applied to the (-) as its first argument, so instead of (list_item - 1)
, I get (1 - list_item)
. I can rewrite it as adding negative one instead of subtracting positive one:
List.map ((+) -1) [1..5];;
List.map (fun x -> x-1) [1..5];; // this works too
我正在寻找一种更具表现力的书写方式,例如((-) _ 1)
,其中_
表示占位符,例如Arc语言.这将导致1
是-
的第二个参数,因此在List.map中它将求值为list_item - 1
.因此,如果您想将divide by 2
映射到列表,则可以编写:
I'm looking for a more expressive way to write it, something like ((-) _ 1)
, where _
denotes a placeholder, like in the Arc language. This would cause 1
to be the second argument to -
, so in List.map, it would evaluate to list_item - 1
. So if you wanted to map divide by 2
to the list, you could write:
List.map ((/) _ 2) [2;4;6] //not real syntax, but would equal [1;2;3]
List.map (fun x -> x/2) [2;4;6] //real syntax equivalent of the above
可以做到这一点还是必须使用(fun x -> x/2)
?似乎最接近占位符语法的是使用带有命名参数的lambda.
Can this be done or do I have to use (fun x -> x/2)
? It seems that the closest we can get to the placeholder syntax is to use a lambda with a named argument.
推荐答案
您可以编写一个翻转函数,例如:
You could write a flip function, something like:
let flip f x y = f y x
List.map (flip (-) 1) [2;4;6]
我的语法可能不正确,我不太熟练F#.
I may have the syntax wrong, I'm not terribly fluent in F#.
这篇关于F#将带有参数的运算符传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!