Recursion in PureScript
Our example demonstrates recursive functions in PureScript. Here’s a classic example of factorial calculation.
In this PureScript code:
We define a recursive
fact
function for calculating factorials. It uses pattern matching to handle the base case (fact 0 = 1
) and the recursive case.In the
main
function, we callfact 7
and print the result.We then define a recursive
fib
function for calculating Fibonacci numbers. In PureScript, we can define local functions usinglet
bindings insidedo
blocks orwhere
clauses. This is similar to the closure approach in the original example.The
fib
function uses guards (|
) to handle different cases, which is idiomatic in PureScript.Finally, we call
fib 7
and print the result.
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
This example demonstrates how PureScript handles recursion, which is a fundamental concept in functional programming languages. The syntax and structure differ from imperative languages, but the core concept of a function calling itself remains the same.