3
votes

I've seen some functions or data-structures in racket use keywords (#:foo), but I haven't been able to conjure my own functions that make use of them. The racket documentation just loosely define that Keywords are similar to Symbols, and sorta just leaves it at that, but writing a function that's supposed to take a keyword as a parameter just leads to the following error: missing argument expression after keyword, which leads me to believe keywords aren't anything like symbols in that they can't just be passed around as values (unless quoted).

The example I'm most familiar with, that uses a keyword, is match:

(...    
  (match foo
    [n #:when (< 10 n) "foo is greater than 10"]
    [_ "undefined"]))

So my question is: How do I make a function or whatever that is capable of taking a Keyword like in the above example?

1

1 Answers

5
votes

Declare the keywords as part of the procedure's parameter definition, for example:

(define (my-sort lst #:reverse reversed? #:comparator cmp)
  (if reversed?
      (reverse (sort lst cmp))
      (sort lst cmp)))

(my-sort '(1 5 2 3 4) #:comparator > #:reverse #t)
=> '(1 2 3 4 5)

(my-sort '(1 5 2 3 4) #:reverse #f #:comparator >)
=> '(5 4 3 2 1)

As @uselpa mentioned in the comments, here's the relevant section in the documentation.