[racket ursers] Keyword question

31 views
Skip to first unread message

Kevin Forchione

unread,
Aug 22, 2019, 4:34:05 PM8/22/19
to Racket-Users List
Hi guys,
Suppose I have something like the following:

(define (f g . args)
(apply g args))

How would I be able to pass keyword arguments to g?

Kevin

Kevin Forchione

unread,
Aug 22, 2019, 6:32:50 PM8/22/19
to Racket-Users List
After racking my brains for the common lisp &allow-other-keys and googling for the scheme/Racket equivalent, stumbling through mzlib/kw and finally a bit of digging through racket procedure documentation I cobbled together an approach that seems to do what I’m after. So I thought I’d share. Here’s an example:

#lang racket


(define (foo #:a (a 0) #:b (b 1) c (d 3) . rst) (list a b c d rst))

(define show
(make-keyword-procedure (λ (kws kw-args f . args) (keyword-apply f kws kw-args args))))

(show foo #:a 10 2 3 4 5 6 7)
=> '(10 1 2 3 (4 5 6 7))

Now apparently any keywords defined for show itself are captured in the kWh and kw-args lists and would need to be filtered out of those lists before tasing them on to f, but that shouldn’t be too difficult.

Kevin

Tim Meehan

unread,
Aug 23, 2019, 1:35:08 AM8/23/19
to Racket-Users List
If it was just passing keyword arguments to your function, you might be able to do it like this:


(define greet
  (lambda (given #:last surname)
    (string-append "Hello, " given " " surname)))

; 'apply' allows you to specify a keyword argument ...
(define (test f . args)
  (apply f args #:last "Doe"))

(test greet "John") ; => "Hello, John Doe"

--
You received this message because you are subscribed to the Google Groups "Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/395CF1DB-3B85-4FFA-9C1B-5566EB2CC60F%40gmail.com.

David Storrs

unread,
Aug 23, 2019, 10:03:59 PM8/23/19
to Tim Meehan, Racket-Users List

(define (f x #:y y #:z [z 10])
  (list x y z))

> (keyword-apply f '(#:y) '(2) '(1))

'(1 2 10)

> (keyword-apply f '(#:y #:z) '(2 3) '(1))

'(1 2 3)

> (keyword-apply f #:z 7 '(#:y) '(2) '(1))

'(1 2 7)


Philip McGrath

unread,
Aug 23, 2019, 10:41:28 PM8/23/19
to David Storrs, Tim Meehan, Racket-Users List
If they do what you want, `curry` and `curryr` support keyword arguments (as of Racket 7.1) and handle lots of cases.

If you do need to use `make-keyword-procedure`, you may want to combine it with `procedure-reduce-keyword-arity-mask`.

-Philip


Reply all
Reply to author
Forward
0 new messages