📅  最后修改于: 2023-12-03 14:44:19.507000             🧑  作者: Mango
Fibonacci sequence is a mathematical sequence of numbers where each number is the sum of the two preceding ones. In programming, Fibonacci sequence is a popular problem-solving task for beginners. Here's how you can implement Fibonacci sequence in ML.
fun fib_seq n =
let
fun fib_helper x y count =
if count = n then y
else fib_helper (y, x + y) (count + 1)
in
if n = 0 then 0
else fib_helper (0, 1) 1
end
The Fibonacci sequence starts with 0, 1 and then the next number is the sum of the two preceding ones. For example, the third number is 0 + 1 = 1, the fourth number is 1 + 1 = 2 and so on.
In this ML code, we define a function fib_seq
that takes an integer n
as an input and returns the n
th Fibonacci number.
The function works by calling a helper function fib_helper
which takes in two integers x
and y
and a counter count
. The count
keeps track of how many numbers have been generated so far, starting from 1.
If count
equals n
, the function returns the Fibonacci number generated so far, which is y
. If not, it calls itself with y
and x + y
as the new values of x
and y
respectively, and count+1
as the new value of count
.
In the fib_seq
function, if n
is 0, it returns 0 as the Fibonacci number. Otherwise, it calls fib_helper
with (0,1)
as the initial values of x
and y
respectively, and 1
as the initial value of count
.
To use this code, you can load it into the SML REPL or compiler and call it like this:
- fib_seq 0;
val it = 0 : int
- fib_seq 10;
val it = 55 : int
- fib_seq 20;
val it = 6765 : int
Fibonacci series is a common task in programming interviews and implementing it in different programming languages can be a good exercise for beginners to practice their problem-solving and programming skills. Implementing Fibonacci sequence in ML demonstrates the use of functional programming concepts like recursion, pattern matching, and immutable variables, typical of languages in the ML family.