【问题标题】:Matching in a point-free style in F#?在 F# 中以无点样式匹配?
【发布时间】:2019-11-17 05:32:15
【问题描述】:

考虑这段代码:

type Fruit = Apple | Banana

let totalCost fruits = 
  fruits
  |> Seq.map (fun fruit -> 
    match fruit with
    | Apple -> 0.50
    | Banana -> 0.70
  )
  |> Seq.sum

我可以重写totalCost 使其更简洁,从而删除fruit 标识符吗?

类似这样的:

// Not real code
let totalCost fruits = 
  fruits
  |> Seq.map (
    match
    | Apple -> 0.50
    | Banana -> 0.70
  )
  |> Seq.sum

【问题讨论】:

  • Nitpick:fruit 是标识符,而不是关键字。关键字是具有特殊句法含义的词,如type、let、fun、match和with。
  • @glennsl 很好。固定!

标签: syntax f# pattern-matching pointfree


【解决方案1】:

您要查找的关键字是function:

|> Seq.map ( 
    function
    | Apple -> 0.50 
    | Banana -> 0.70
)

function 被脱糖为fun x -> match x with

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多