Recursion in PureScript
Our example demonstrates recursive functions in PureScript. Here’s a classic example of factorial calculation.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
-- This `fact` function calls itself until it reaches the
-- base case of `fact 0`.
fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n - 1)
main :: Effect Unit
main = do
log $ show $ fact 7
-- In PureScript, we can define recursive functions using let bindings
-- inside do blocks or where clauses
let
fib :: Int -> Int
fib n
| n < 2 = n
| otherwise = fib (n - 1) + fib (n - 2)
log $ show $ fib 7
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:
$ pulp run
5040
13
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.