Recursion Worksheet

Table of Contents

1. Recursion

For recursion to work we need the function to take itself as a parameter.

{bind [fact = {(self n) => ...
                           ...
                           ...
                           {self self {- n 1}}}
                           ...
                           ...}]
        {fact fact 4}}

1.1. Recursion worksheet

  ;; exercise 0: Using the binding form, give the name
    ;; `f` to the function that accepts an argument `x` and computes
    ;; x^2 + 4x + 4. Apply `f` to seven.

    {bind [f = {(x) =>
                    {+ {+ {* x x} {* 4 x}} 4}}]
          {f 7}}

    ;; exercise 1: Use the trick discussed in class to define
    ;; a `fact` function that computes the factorial of a given
    ;; number. Use it to compute the factorial of 12.

    {bind [fact = {(self n) =>
                            {if {<= n 0}
                                1
                                {* n {self self {- n 1}}}}}]
          {fact fact 4}}


    ;; exercise 2: Define a 'pow' function that accepts a base
    ;; and a (natural number) exponent, and computes the base to
    ;; the power of the exponent. Don't worry about non-natural
    ;; number exponents (6^1.5, 5^-4).

    {bind [pow = {(self base n) =>
                           {if {<= n 0}
                           1
                           {* base {self self base {- n 1}}}}}]
          {pow pow 6 3}}

    ;; exercise 3: use `fact` and `pow` to build a "sin" function
    ;; that accepts a number x and a number of terms `n`, and computes
    ;; (sin x) using `n` terms of the taylor expansion. (Note that
    ;; this is a little ambigious; do zero-coefficient terms count?
    ;; You can go either way on this.) Use this function to compute
    ;; the sine of 1 radian to an error of no more than ten to the minus
    ;; 30th.

THIS AINT RIGHT
    {bind [pow = {(self base n) =>
                           {if {<= n 0}
                           1
                           {* base {self self base {- n 1}}}}}]
          [fact = {(self n) =>
                            {if {<= n 0}
                                1
                                {* n {self self {- n 1}}}}}]
          {bind [sin = {(self x n) =>
                             {if {<= n 0}
                                 1
                                 {{- x {/ {pow x {- n 2} {fact {- n 2}}}}}}}}]
                (sin sin 5 10)}}


Date: 2024-10-25 Fri 00:00

Author: Anthony Rossi

Created: 2024-10-27 Sun 18:00