Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Created January 24, 2020 20:53
Show Gist options
  • Save kmicinski/6fa76421753d3b513ed197fb2254cfab to your computer and use it in GitHub Desktop.
Save kmicinski/6fa76421753d3b513ed197fb2254cfab to your computer and use it in GitHub Desktop.
#lang racket
;; Reverse a list using tail recursion
;; This is very natural using tail recursion,
;; since most things get reversed anyway.
(define (rev-lst l)
;; you probably want to use a helper function
(define (helper l acc)
'todo)
'todo)
;; Return the sum of all elements in a list
;; that are greater than 50. Use tail recursion
(define (sum-gt-50 l)
'todo)
;; Applies the function f to each element of l
(define (map f l)
(match l
['() '()]
[`(,fst . ,rst) (cons (f fst) (map f rst))]))
;; Exercise: define map-tail, which uses tail-recursion
;; to define map
(define (map-tail f l)
'todo)
;; Exercise: figure out what fold-left does
(define (fold-left f acc l)
(match l
['() acc]
[`(,fst . ,rst)
(fold-left f (f fst acc) rst)]))
(define (mul x y) (* x y))
;; All of the following do roughly the same thing
(define (multiply-all l)
(fold-left mul 1 l))
(define (multiply-all-again l)
(fold-left (lambda (x y) (* x y)) 1 l))
(define (multiply-all-yet-again l) (fold-left * 1 l))
(define (fold-right f unit l)
(match l
['() unit]
[`(,fst . ,rst)
(f fst (fold-right f unit rst))]))
;; exercise: use fold-left to sum the elements in a list
;; exercise: use fold-right to sum the elements in a list
;; exercise: use fold-left to filter out all elements of a
;; list that are not strings
;; exercise: use fold-left to write a function that concatenates
;; all of the strings in a list together into one big string. Use
;; (string append s0 s1). Also be sure that you get the order right!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment