Tutorial by Examples

#lang racket (define (sum-of-list l) (if (null? l) 0 (+ (car l) (sum-of-list (cdr l))))) (sum-of-list '(1 2 3 4 5)) ;; => 15
#lang racket (letrec ([sum-of-list (λ (l) (if (null? l) 0 (+ (car l) (sum-of-list (cdr l)))))]) (sum-of-list '(1 2 3 4 5))) ;; => 15 It is possible to write mutually recursive functions with letrec: #lang ...
A normal let form binds each value to its corresponding identifier, before executing the body. With a "named let", the body can then recursively be re-executed, passing a new value for each identifier. #lang racket (let sum-of-list ([l '(1 2 3)]) (if (null? l) 0 (+ (car ...
#lang racket (require mzlib/etc) ((rec sum-of-list (λ (l) (if (null? l) 0 (+ (car l) (sum-of-list (cdr l)))))) '(1 2 3 4 5)) ;; => 15 ;; Outside of the rec form, sum-of-list gives an error: ;; sum-of-list: undefined; ;; cannot reference an identifier befor...
It is common practice to use higher order functions instead of recursion, if there is a higher order function which expresses the right recursion pattern. In our case, sum-of-numbers can be defined using foldl: #lang racket (define (sum-of-numbers l) (foldl + 0 l)) (sum-of-numbers '(1 2 3 4 5)...

Page 1 of 1