Recursion in Haskell
Haskell supports recursive functions. Here’s a classic example.
In this Haskell version:
We define the
fact
function using pattern matching. The base casefact 0 = 1
is explicitly stated, and the recursive case follows.The
main
function is where we execute our code.In Haskell, we don’t need to explicitly declare recursive functions before defining them, as we do with closures in some other languages. We can define recursive functions directly, as shown with the
fib
function.The
fib
function uses guards (|
) instead of if-else statements to define its behavior for different input conditions.
To run this program, save it in a file named recursion.hs
and use the following commands:
This will compile the Haskell code and then run the resulting executable, which outputs the factorial of 7 and the 7th Fibonacci number.
Haskell’s strong support for recursion and pattern matching makes it particularly well-suited for implementing recursive algorithms in a clear and concise manner.