F#,前移第一个参数 [英] F#, Pipe-forward first argument
问题描述
与此问题非常相似: F#管道优先参数
Quite similar to this question: F# pipe first parameter
我目前正在学习F#和函数编程,我想知道是否存在一种简便的方法来传递第一个参数(而不是最后一个参数).
I am currently learning F# and functional programming, and I want to know if there is an easy way to pipe-forward a first argument (instead of last argument).
例如,如果我想传递最后一个参数,它看起来非常干净:
For example, if I want to pipe forward the last argument, it looks very nice and clean:
[4;5;6]
|> List.append [1;2;3]
// Result: [1;2;3;4;5;6]
如果我想传递第一个参数,可以使用"fun x->"函数,但是我只是想知道是否有更干净的方法.
If I want to pipe-forward the first argument, I can use a "fun x ->" function, but I am just curious if there is a cleaner way.
[1;2;3]
|> fun x -> List.append x [4;5;6]
// Result: [1;2;3;4;5;6]
非常感谢您.
P.S.我的同事只是帮助我解决了这个问题.但是,如果您对F#初学者有任何建议,我将不胜感激.谢谢.
P.S. My coworker just helped me with this problem. But I would appreciate any help if you have any suggestions for an F# beginner. Thank you.
推荐答案
当参数的顺序不方便时,您始终可以转换函数本身,使其以不同的顺序接受参数:
When the order of arguments is inconvenient, you can always transform the function itself to make it take the arguments in a different order:
let flip f x y = f y x
[1; 2; 3]
|> (flip List.append) [4; 5; 6]
转换功能在许多情况下都很有用.这是功能性程序员的食粮.
Transforming functions is useful in many contexts. It is a functional programmer's bread and butter.
但是最后,我相信可读性是最重要的:程序的读取比编写的频率要高得多.当我发现自己处于类似情况下,并且由于某种原因不想命名中间值或使用lambda表达式时,我为自己定义了一个直观易懂的函数:
But in the end, I believe, readability is most important: programs are read incomparably more often than they are written. When I find myself in a similar situation, and I don't want to name the intermediate value or use a lambda expression for some reason, I define myself a function that would be intuitive to understand:
let prependTo a b = List.append b a
[1; 2; 3]
|> prependTo [4; 5; 6]
这篇关于F#,前移第一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!