是否可以与F#中的分解序列匹配? [英] Is it possible to match with decomposed sequences in F#?

查看:57
本文介绍了是否可以与F#中的分解序列匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎还记得F#的较旧版本,当匹配序列(如列表)时允许结构分解.有没有一种方法可以使用列表语法,同时使序列保持懒惰?我希望避免对Seq.head和Seq.skip 1的大量调用.

I seem to remember an older version of F# allowing structural decomposition when matching sequences just like lists. Is there a way to use the list syntax while keeping the sequence lazy? I'm hoping to avoid a lot of calls to Seq.head and Seq.skip 1.

我希望有这样的东西:

let decomposable (xs:seq<'a>) =
   match xs with
   | h :: t -> true
   | _ -> false
seq{ 1..100 } |> decomposable

但这仅处理列表,并在使用序列时给出类型错误.使用List.of_seq时,似乎可以评估序列中的所有元素,即使它是无限的.

But this only handles lists and gives a type error when using sequences. When using List.of_seq, it seems to evaluate all the elements in the sequence, even if it is infinite.

推荐答案

如果在PowerPack中使用LazyList类型,它将具有称为LazyList.Nil和LazyList.Cons的活动模式.

If you use the LazyList type in the PowerPack, it has Active Patterns called LazyList.Nil and LazyList.Cons that are great for this.

seq/IEnumerable类型并不特别适合模式匹配;我强烈建议为此使用LazyList. (另请参见

The seq/IEnumerable type is not particulaly amenable to pattern matching; I'd highly recommend LazyList for this. (See also Why is using a sequence so much slower than using a list in this example.)

let s = seq { 1..100 }
let ll = LazyList.ofSeq s
match ll with
| LazyList.Nil -> printfn "empty"
| LazyList.Cons(h,t) -> printfn "head: %d" h

这篇关于是否可以与F#中的分解序列匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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