【问题标题】:Feeding tuple into function such as printfn将元组输入到 printfn 等函数中
【发布时间】:2013-12-13 13:58:11
【问题描述】:

我想给 printf 函数一个元组:

let tuple = ("Hello", "world")
do printfn "%s %s" tuple

这当然行不通,编译器首先说,它需要string 而不是string*string。我是这样写的:

let tuple = ("Hello", "world")
do printfn "%s %s" <| fst tuple

然后编译器合理地注意到现在我有string -&gt; unit 类型的函数值。说得通。我会写

let tuple = ("Hello", "world")
do printfn "%s %s" <| fst tuple <| snd tuple

它对我有用。但我想知道,是否有任何方法可以做得更好,比如

let tuple = ("Hello", "world")
do printfn "%s %s" <| magic tuple

我的问题是我无法得到 printf 需要哪种类型才能打印两个参数。 magic 函数是什么样的?

【问题讨论】:

    标签: f# operators tuples


    【解决方案1】:

    你想要

    let tuple = ("Hello", "world")   
    printfn "%s %s" <|| tuple
    

    注意&lt;|| 中的双|| 而不是&lt;| 中的单个|

    见:&lt;||

    你也可以这样做

    let tuple = ("Hello", "world")
    tuple
    ||> printfn "%s %s"
    

    还有其他类似的operators,如|&gt;||&gt;|||&gt;&lt;|&lt;||&lt;|||

    使用fstsnd 的惯用方法是

    let tuple = ("Hello", "world")
    printfn "%s %s" (fst tuple) (snd tuple)
    

    您通常看不到使用 ||> 或 解构。

    析构表达式采用复合类型并将其分解为多个部分。

    所以对于tuple ("Hello", "world"),我们可以创建一个析构函数,将元组分成两部分。

    let (a,b) = tuple
    

    我知道这对于 F# 的新手来说可能看起来像一个元组构造函数,或者可能看起来更奇怪,因为我们绑定了两个值,(注意我说的是绑定和未分配),但它需要具有两个值的元组并将其解构为两个独立的值。

    所以这里我们使用解构表达式。

    let tuple = ("Hello", "world")
    let (a,b) = tuple
    printfn "%s %s" a b
    

    或更常见

    let (a,b) = ("Hello", "world")
    printfn "%s %s" a b
    

    【讨论】:

    • @Rustam 我建议不要使用magic,因为它不是一种标准的做事方式。 @GuyCoder 列出了一些更惯用的方法来完成你想做的事情。
    • @mydogisbox 当然,我只是想了解如何做到这一点
    • 第一个 MSDN 链接已损坏,因此可以在 fsharp.github.io/fsharp-core-docs/reference/… 找到 ||&gt; 文档
    • @MattMS 谢谢。由于该帖子是知识共享,您可以只修复链接而不是发表评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多