Skip to content

Instantly share code, notes, and snippets.

@Metaxal
Last active December 29, 2020 16:46
Show Gist options
  • Save Metaxal/54caeea9f2cea5e35331cfc80408fa94 to your computer and use it in GitHub Desktop.
Save Metaxal/54caeea9f2cea5e35331cfc80408fa94 to your computer and use it in GitHub Desktop.
Helpers to define wrappable functions and wrappers (proof of concept)
#lang racket
(require syntax/parse/define
(for-syntax racket/syntax
racket/base))
;;; License: [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) or
;;; [MIT license](http://opensource.org/licenses/MIT) at your option.
(define no-value (gensym))
(define-for-syntax (syntax->keyword stx)
(string->keyword (format "~a" (syntax-e stx))))
(define-simple-macro (define* (fun pvar:id ...
(~alt (~seq #:? [var:id val])
(~seq #:? var2:id))
...)
body ...)
#:with (kwd ...) (map syntax->keyword (syntax->list #'(var ...)))
#:with (kwd2 ...) (map syntax->keyword (syntax->list #'(var2 ...)))
(define (fun pvar ... (~@ kwd [var val]) ... (~@ kwd2 [var2 no-value]) ...)
(let ([var (if (eq? var no-value) val var)] ...)
body ...)))
;;; Example:
;; Base function that creates a new default
(define* (my-dict-ref dico key #:? [default (λ () (error (format "Key not found: ~a" key)))])
(dict-ref dico key default))
;; Wrapper function with a pass-through default argument
(define* (my-curried-dict-ref key #:? default)
(λ (dico) (my-dict-ref dico key #:default default)))
#|
> (define d '((a . 3) (b . 2)))
> (my-dict-ref d 'a)
3
> (my-dict-ref d 'aa)
Key not found: aa
> (my-dict-ref d 'aa #:default 4)
4
> ((my-curried-dict-ref 'a) d)
3
> ((my-curried-dict-ref 'aa) d)
Key not found: aa
> ((my-curried-dict-ref 'aa #:default 4) d)
4
|#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment