如何在List.map之后使用List.exists而不需要额外的let绑定?

时间:2012-02-23 14:29:34

标签: f#

type ProcessAttachmentResult = ValidAttachment | InvalidAttachment

let processAttachment ( attachment : Attachment ) =
    if attachment.Name ="test.txt" then
       printfn "%s valid" 
       ValidAttachment
    else 
       printfn "%s invalid" attachment.Name
       InvalidAttachment

// attachments is of type List<Attachment>
let processedAttachments = attachments |> List.map processAttachment

// ProcessAttachmentResult list
let emailContainsValidAttachments = 
   List.exists ( fun r -> r = ValidAttachment) processedAttachments

match emailContainsValidAttachments with
| true -> move email toProcessedFolder 
| _ -> move email toErrorFolder 

如何更改最后两个let绑定并匹配单个绑定?

我试过

attachments |> List.map processAttachment |> List.exists (fun r -> r = ValidAttachment)

但这给出了:

  

此表达式应为ProcessAttachmentResult list类型,但此处的类型为bool

2 个答案:

答案 0 :(得分:2)

作为评论中提到的pad,您的方法没有任何问题。您必须意外地重新定义了一些内置函数(如List.exists)。要检查这一点,请尝试打开一个新的F#脚本文件并粘贴以下代码。

基本上你的代码添加了缺少的声明,并且类型检查就好了:

type ProcessAttachmentResult = ValidAttachment | InvalidAttachment 
type Attachment = { Name : string }
let attachments = [] 
let move a b = ()
let email = 0
let toProcessedFolder = ""
let toErrorFolder = ""

let processAttachment ( attachment : Attachment ) = 
    if attachment.Name = "test.txt" then 
       printfn "%s valid"  // TOMAS: Minor issue here - you missed the argument
       ValidAttachment 
    else  
       printfn "%s invalid" attachment.Name 
       InvalidAttachment 

// attachments is of type List<Attachment> 
let processedAttachments = attachments |> List.map processAttachment 

// ProcessAttachmentResult list 
let emailContainsValidAttachments =  
   List.exists ( fun r -> r = ValidAttachment) processedAttachments 

match emailContainsValidAttachments with 
| true -> move email toProcessedFolder  
| _ -> move email toErrorFolder  

// TOMAS: No problem here - this type-checks without errors
attachments 
|> List.map processAttachment 
|> List.exists ( fun r -> r = ValidAttachment)

答案 1 :(得分:1)

似乎你需要:

let emailContainsValidAttachments = 
    List.exists ( fun r -> r = ValidAttachment) (List.map attachments processAttachment)

由于某种原因,参数顺序在existsmap中有所不同。