Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Created January 24, 2020 02:27
Show Gist options
  • Save kmicinski/5d11aac7924e4563a2f423fa8be7957c to your computer and use it in GitHub Desktop.
Save kmicinski/5d11aac7924e4563a2f423fa8be7957c to your computer and use it in GitHub Desktop.
#lang racket
(define l `(,(+ 1 2) 3 hello))
(define l2 `(,(+ 1 2) 3 'hello))
(equal? l l2) ;; #f, there's an *extra* tick in l2
(define (tree? t)
(match t
[`(empty-tree) #t]
[`(node ,(? number? n)) #t]
[`(tree ,(? number? n) ,(? tree? t0) ,(? tree? t1)) #t]
[_ #f]))
(define (tree-contains? t n)
(match t
[`(empty-tree) #f]
[`(node ,(? number? n0)) (= n0 n)]
[`(tree ,(? number? n0) ,(? tree? t0) ,(? tree? t1))
(cond [(= n0 n) #t]
[(< n n0) (tree-contains? t0 n)]
[(> n n0) (tree-contains? t1 n)])]))
;; Exercise (optional): define (tree-insert t n) that inserts
;; a number n into a tree if it does not exist, returning a
;; new tree. This might be a fairly tough one.
;; Here's a definition of graph? in simpler terms
(define (graph? lst)
(define (edge? e)
(match e
;; An edge is a list of two elements, both of which are symbols
[`(,(? symbol? n0) ,(? symbol? n1)) #t]
;; otherwise, not an edge
[_ #f]))
;; helper function to decide if each element of lst matches
(define (each-an-edge? lst)
(match lst
;; when nothing left to check, each matches
[`() #t]
;; otherwise, check this one and all rest
[`(,fst . ,rst) (and (edge? fst) (each-an-edge? rst))]))
;; is the graph a list?
(and (list? lst)
(each-an-edge? lst)))
;; exercise (opt): write some example graphs
;; exercise (opt): write an algorithm to find all of the nodes of the graph
;; consider using (set) and (set-add ..)
(define (graph-again? glst)
(and (list? glst)
;; andmap is a function that applies an anonymous
;; function to each element of the list
(andmap
(lambda (element)
;; match each element
(match element
;; if both symbols? true
[`(,(? symbol? src) ,(? symbol? dst)) #t]
[_ #f]))
;; map across all of glst
glst)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment