如何进一步优化 F# 中的拆分?
此代码通过一个谓词将列表分成两部分,该谓词采用列表并在拆分时返回 false。
let split pred ys =
let rec split' l r =
match r with
| [] -> []
| x::xs -> if pred (x::l) then x::(split' (x::l) xs) else []
let res = split' [] ys
let last = ys |> Seq.skip (Seq.length res) |> Seq.toList
(res, last)
有人知道在 F# 中更优化、更简单的方法吗?
This code is splitting a list in two pieces by a predicate that take a list and return false in the moment of splitting.
let split pred ys =
let rec split' l r =
match r with
| [] -> []
| x::xs -> if pred (x::l) then x::(split' (x::l) xs) else []
let res = split' [] ys
let last = ys |> Seq.skip (Seq.length res) |> Seq.toList
(res, last)
Do someone knows more optimal and simpler ways to do that in F#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,你可以让它尾递归,但随后你必须反转列表。您不想折叠它,因为它可以随时退出递归循环。我做了一些测试,并且反转列表足以通过尾递归来弥补。
与 Brian 类似的版本是尾递归并采用单值谓词。
这与库函数分区不同,因为一旦谓词返回 false 类型(如 Seq.takeWhile),它就会停止获取元素。
Well you can make it tail recursive but then you have to reverse the list. You wouldn't want to fold it since it can exit out of the recursive loop at any time. I did a little testing and reversing the list is more than made up for by tail recursion.
A version similar to Brian's that is tail recursive and takes a single value predicate.
This is different from the library function partition in that it stops taking elements as soon as the predicate returns false kind of like Seq.takeWhile.
不是尾递归,但是:
Not tail-recursive, but:
这是一些文件夹方式:
Here is some foldr way: