在F#中将另一个参数插入管道 [英] Piping another parameter into the line in F#

查看:70
本文介绍了在F#中将另一个参数插入管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

管道中进入管道的参数仅对接受一个参数的功能有效吗? 如果我们在克里斯·史密斯的页面上查看示例

Is piping parameter into line is working only for functions that accept one parameter? If we look at the example at Chris Smiths' page,


// Using the Pipe-Forward operator (|>)
let photosInMB_pipeforward =
    @"C:\Users\chrsmith\Pictures\"
    |> filesUnderFolder
    |> Seq.map fileInfo
    |> Seq.map fileSize
    |> Seq.fold (+) 0L 
    |> bytesToMB

他的filesUnderFolder函数只需要rootFolder参数, 如果函数需要两个参数,即
,该怎么办? let filesUnderFolder size rootFolder

where his filesUnderFolder function was expecting only rootFolder parameter, what if the function was expecting two parameters, i.e.
let filesUnderFolder size rootFolder

然后这不起作用:


// Using the Pipe-Forward operator (|>)
let size= 4
let photosInMB_pipeforward =
    @"C:\Users\chrsmith\Pictures\"
    |> filesUnderFolder size
    |> Seq.map fileInfo
    |> Seq.map fileSize
    |> Seq.fold (+) 0L 
    |> bytesToMB

因为我可以定义
let inline (>>) f g x y = g(f x y)
我认为我应该能够将管道运算符与具有多个输入参数的函数一起使用,对吗?我想念什么?

Since I can define
let inline (>>) f g x y = g(f x y)
I think I should be able to use pipeline operator with functions having multiple input parameters, right? What am I missing?

推荐答案

在混合使用管道运算符和咖喱参数时,请注意传递参数的顺序.

When mixing pipeline operators and curried arguments be aware of the order you pass arguments with.

let size = 4
let photosInMB_pipeforward =
    size, @"C:\Users\chrsmith\Pictures\"
    ||> filesUnderFolder
    |> Seq.map fileInfo
    |> Seq.map fileSize
    |> Seq.fold (+) 0L 
    |> bytesToMB

考虑一下,好像编译器像这样在函数及其参数周围加上括号.

Think about it as if the compiler is putting parentheses around the function and its parameters like this.

@"C:\Users\chrsmith\Pictures\" |> filesUnderFolder size
成为
@"C:\Users\chrsmith\Pictures\" |> (filesUnderFolder size)

(filesUnderFolder size) @"C:\Users\chrsmith\Pictures\"

@"C:\Users\chrsmith\Pictures\" |> filesUnderFolder size
becomes
@"C:\Users\chrsmith\Pictures\" |> (filesUnderFolder size)
or
(filesUnderFolder size) @"C:\Users\chrsmith\Pictures\"

乱序示例

let print2 x y = printfn "%A - %A" x y;;

(1, 2) ||> print2;;
1 - 2

1 |> print2 2;;
2 - 1

带有三个参数

let print3 x y z = printfn "%A - %A - %A" x y z;;

(1, 2, 3) |||> print3;;
1 - 2 - 3

(2, 3) ||> print3 1;;
1 - 2 - 3

3 |> print3 1 2;;
1 - 2 - 3

定义

let inline (|>) x f = f x

let inline (||>) (x1,x2) f = f x1 x2

let inline (|||>) (x1,x2,x3) f = f x1 x2 x3

这篇关于在F#中将另一个参数插入管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆