Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Last active February 10, 2023 01:23
Show Gist options
  • Select an option

  • Save kmicinski/ce83d693da887d46d1197483a8ce5f6b to your computer and use it in GitHub Desktop.

Select an option

Save kmicinski/ce83d693da887d46d1197483a8ce5f6b to your computer and use it in GitHub Desktop.
#lang racket
(define x '(this (is an) s expression))
;; Write a function that takes an input list l
;; and adds 2 to every element of the list
;; assume all elements are numbers
#;(define (add-two-to-each l)
(define addtwo (lambda (x) (+ x 2)))
;(define (addtwo x) (+ x 2))
(if (empty? l)
'()
(cons (addtwo (first l)) (add-two-to-each (rest l)))))
;; Same thing, but subtract 2 from each element
#;(define (sub-two-from-each l)
(define subtwo (lambda (x) (- x 2)))
(if (empty? l)
'()
(cons (subtwo (first l)) (sub-two-from-each (rest l)))))
#;(define (invert l)
(if (empty? l)
'()
(cons (- (first l)) (invert (rest l)))))
(define (map f l)
(if (empty? l)
'()
(cons (f (first l)) (map f (rest l)))))
(define (add-two-to-each l)
;(define addtwo (λ (x) (+ x 2)))
(define (addtwo x) (+ x 2))
(map addtwo l))
(define (sub-two-from-each l)
(map (λ (x) (- x 2)) l))
(define (invert l)
(map (λ (x) (- x)) l))
(define (sum l)
(if (empty? l)
0
(+ (first l) (sum (rest l)))))
;; Use map to write a function, add1-to-numbers
;; which walks over a list l and--for each element
;; x--if x satisfies number?, then add 1 to x, otherwise
;; leave it alone
;; (add1-to-numbers '(1 "h" 3)) --> '(2 "h" 4)
(define (add1-to-numbers l)
(map (λ (x) ;; x is an element of l, each element of l
(if (number? x)
(add1 x)
;; otherwise, not a number
x))
l))
;(define x 23)
(define y 42)
(define (tree? t)
(match t
['empty #t]
[`(tree ,(? number?) ,(? tree?) ,(? tree?)) #t]
[_ #f]))
(define/contract (tree-map f t)
(-> (-> any/c any/c) tree? tree?)
(match t
['empty 'empty]
[`(tree ,e ,t0 ,t1)
`(tree ,(f e) ,(tree-map f t0) ,(tree-map f t1))]))
(tree-map add1 '(tree 4 (tree 6 empty empty) empty))
(define (spaces n) (make-string n #\space))
;; let's pretend that characters are all contiguous and start from the first column
;; '((0 #\a) (1 #\b)) --> "ab"
;; here's a helper function h which takes as input the list l
;; i is "where to start from when I insert spaces"
(define (h l i)
(if (empty? l)
""
;; l is something like... '((3 0 #\a) (3 1 #\b))
;; (first l) is something like '(0 #\a)
;; (second (first l)) is the character I want to render
;; (first (first l)) is the current column I'm printing at
(let ([column (first (first l))]
[char (second (first l))])
(string-append
(spaces (- column i))
(make-string 1 char)
(h (rest l) (add1 column))))))
(h '((1 #\a) (2 #\b) (4 #\c)) 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment