gpt4 book ai didi

f# - 在F#中生成斐波那契数列

转载 作者:行者123 更新时间:2023-12-03 13:38:24 27 4
gpt4 key购买 nike

我刚刚开始使用VS2010学习F#,下面是我第一次尝试生成Fibonacci系列的方法。我想做的是建立一个所有小于400的数字的列表。

let fabList = 
let l = [1;2;]
let mutable a = 1
let mutable b = 2
while l.Tail < 400 do
let c = a + b
l.Add(c)
let a = b
let b = c


我的第一个问题是,在最后一条语句上,我在最后一行收到一条错误消息“在表达式中此点或之前的不完整结构化构造”。我不明白我在做什么错。

尽管这似乎是一种以相当有效的方式构建列表的明显方法(来自c ++ / C#程序员),但据我对f#的了解很少,但这似乎并不是执行该程序的正确方法。我在这种感觉上正确吗?

最佳答案

首先,您使用let就像是对变量进行突变的语句一样,但事实并非如此。在F#中,let用于声明一个新值(它可能会隐藏任何以前相同名称的值)。如果要使用变异来编写代码,则需要使用类似以下内容的代码:

let c = a + b  // declare new local value
l.Add(c)
a <- b // mutate value marked as 'mutable'
b <- c // .. mutate the second value


代码的第二个问题是,您试图通过向其添加元素来使F#列表发生突变-F#列表是不可变的,因此一旦创建它们,就无法对其进行修改(特别是,没有 Add成员!) 。如果要使用变异来编写此代码,可以编写:

let fabList = 
// Create a mutable list, so that we can add elements
// (this corresponds to standard .NET 'List<T>' type)
let l = new ResizeArray<_>([1;2])
let mutable a = 1
let mutable b = 2
while l.[l.Count - 1] < 400 do
let c = a + b
l.Add(c) // Add element to the mutable list
a <- b
b <- c
l |> List.ofSeq // Convert any collection type to standard F# list


但是,正如其他人已经指出的那样,以这种方式编写代码并不是惯用的F#解决方案。在F#中,您将使用不可变列表和递归而不是循环(例如 while)。例如这样:

// Recursive function that implements the looping
// (it takes previous two elements, a and b)
let rec fibsRec a b =
if a + b < 400 then
// The current element
let current = a + b
// Calculate all remaining elements recursively
// using 'b' as 'a' and 'current' as 'b' (in the next iteration)
let rest = fibsRec b current
// Return the remaining elements with 'current' appended to the
// front of the resulting list (this constructs new list,
// so there is no mutation here!)
current :: rest
else
[] // generated all elements - return empty list once we're done

// generate list with 1, 2 and all other larger fibonaccis
let fibs = 1::2::(fibsRec 1 2)

关于f# - 在F#中生成斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2845744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com