Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Collections 运行时采取的总值小于值_Collections_F#_Take - Fatal编程技术网

Collections 运行时采取的总值小于值

Collections 运行时采取的总值小于值,collections,f#,take,Collections,F#,Take,我试图生成一个偶数整数列表,而列表中的项之和不等于给定的数字。 例如,如果阈值k为20,则预期输出为[0;2;4;6;8] 我可以生成一个最大值小于阈值的列表,如下所示: let listOfEvenNumbersSmallerThanTwenty = Seq.unfold (fun x -> Some(x, x + 1)) 0 // natural numbers |> Seq.filter (fun x -> x % 2 = 0) // even numbe

我试图生成一个偶数整数列表,而列表中的项之和不等于给定的数字。 例如,如果阈值k为20,则预期输出为[0;2;4;6;8]

我可以生成一个最大值小于阈值的列表,如下所示:

let listOfEvenNumbersSmallerThanTwenty =
    Seq.unfold (fun x -> Some(x, x + 1)) 0 // natural numbers
    |> Seq.filter (fun x -> x % 2 = 0) // even numbers
    |> Seq.takeWhile (fun x -> x <= 20)
    |> List.ofSeq
listofevennumbersmallerthantwenty=
Seq.unfold(乐趣x->Some(x,x+1))0//自然数
|>Seq.filter(乐趣x->x%2=0)//偶数
|>Seq.takeWhile(乐趣x->x列表)
(我知道我可以将“展开”和“过滤”组合为一些(x,x+2),但此任务用于教育目的)

我设法创建了一个不同的列表,其运行总数小于阈值:

let runningTotal =
    listOfEvenNumbersSmallerThanTwenty 
    |> Seq.scan (+) 0
    |> Seq.filter (fun x -> x < 20)
    |> List.ofSeq
let runningTotal=
二十个以上的七个数字列表
|>序列扫描(+)0
|>顺序过滤器(乐趣x->x<20)
|>表1.1

但为了做到这一点,我在ListofEventumbersSmallerthantwenty中设置了阈值(这比需要的项多得多),并丢失了初始序列。我也尝试使用可变值来找到它,但并不真正喜欢这种方法。

我认为这是一个非常优雅的解决方案(尽管不是最有效的):

让evens=Seq.initInfinite(乐趣i->2*i)
Seq.initInfinite(乐趣i->Seq.take i均衡)
|>Seq.takeWhile(乐趣Seq->
序号总和序号最后一个序号
|>表1.1

您可以创建一个小型谓词函数来封装可变和

let sumLessThan threshold =
    let mutable sum = 0
    fun x ->
        sum <- sum + x
        sum < threshold

封装可变状态时使用可变状态并没有什么坏处(检查模块中可变变量的用法)

谢谢@Sergey的回答。我目前正在尝试学习F#,我认为我可能已经过度避免了可变状态。我认为需要进一步的经验才能知道何时选择可变状态才是最好的方法。如果尝试并行运行,该解决方案会受到影响吗?@Thanasik好吧,它不应该并行运行l、 与其他序列函数一样-exists、forAll、fold等。甚至很难想象如何并行执行此操作-您将遇到两个瓶颈,共享状态必须在线程之间同步-从共享源序列读取项并检查共享和。这看起来像是同步多线程处理e、 顺便说一句,
Seq.takeWhile
Seq.initInfinite
,尤其是
Seq.scan
使用可变状态。因此,这不是为了避免突变,而是为了声明性而不是强制性。IMHO
Seq.takeWhile(Sumlesthan 20)
非常声明性:)
let sumLessThan threshold =
    let mutable sum = 0
    fun x ->
        sum <- sum + x
        sum < threshold
Seq.initInfinite ((*) 2) |> Seq.takeWhile (sumLessThan 20)