Skip to content

Instantly share code, notes, and snippets.

@voila
Created March 4, 2013 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voila/5085531 to your computer and use it in GitHub Desktop.
Save voila/5085531 to your computer and use it in GitHub Desktop.
Higher-order list operations exercices
#lang racket
;; http://matt.might.net/articles/higher-order-list-operations/
;; Rewrite abstract mapping and folding using matching.
(define (abs-map kons nil f lst)
(match lst
['() nil]
[(cons hd tl)
(kons (f hd) (abs-map kons nil f tl))]))
(abs-map cons '() identity '(1 2 3 4)) ; => '(1 2 3 4)
(define (foldr/match kons nil lst)
(match lst
('() nil)
((cons hd tl)
(kons (car lst) (foldr/match kons nil (cdr lst))))))
(foldr/match cons '() '(1 2 3 4)) ; => '(1 2 3 4)
(foldr/match + 0 '(1 2 3 4)) ; => 10
;; Rewrite mapping, filtering and folding using continuations.
(define (map-k f lst k)
(match lst
('() (k null))
((cons hd tl)
(map-k f (cdr lst) (λ (mapped-lst) (k (cons (f hd) mapped-lst)))))))
(map-k add1 '(1 2 3 4) identity) ; => '(2 3 4 5)
(define (filter-k p? lst k)
(match lst
('() (k null))
((cons hd tl)
(filter-k p?
(cdr lst)
(λ (fl-lst) (k (if (p? hd) (cons hd fl-lst) fl-lst)))))))
(filter-k even? '(1 2 3 4) identity) ; => '(2 4)
(define (fold-k f nil lst k)
(match lst
('() (k nil))
((cons hd tl)
(fold-k f nil (cdr lst) (λ (acc) (k (f hd acc)))))))
(fold-k + 0 '(1 2 3 4) identity) ; => 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment