Passing keywords from a list

45 views
Skip to first unread message

Dimaugh Silvestris

unread,
Nov 26, 2020, 3:53:31 AM11/26/20
to Racket Users
Is it possible to reproduce this behavior
((lambda (#:color color #:size size) (display (cons color size))) #:color "red" #:size 3)
when what I have is a list such as '(#:color "red" #:size 3) ?
How can I feed keyword arguments stored in a list as symbols in a way that doesn't involve parsing manually?

Sorawee Porncharoenwase

unread,
Nov 26, 2020, 4:06:26 AM11/26/20
to Dimaugh Silvestris, Racket Users

If you are OK with preprocessing the argument list into a dictionary, then you can use keyword-apply/dict.

For example:

#lang racket

(require racket/dict)

(define proc (lambda (#:color color #:size size) (display (cons color size))))
(define args '(#:color "red" #:size 3))
(define args*
  (for/hash ([chunk (in-slice 2 args)])
    (values (first chunk) (second chunk))))

(keyword-apply/dict proc args* '())

--
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/06a1b45b-77ca-4595-b5b6-0b4ce01fe026n%40googlegroups.com.

Dimaugh Silvestris

unread,
Nov 26, 2020, 4:42:40 AM11/26/20
to Racket Users
Thanks! Your answer led me to find keyword-apply, so I just wrote (I use def as abbreviation for define):

(def (parse-args xs)
  (def (fn ks kvs vs xs)
    (cond [(empty? xs)  (map reverse (list ks kvs vs))]
          [(keyword? (car xs))
           (fn (cons (car xs) ks) (cons (cadr xs) kvs) vs (drop xs 2))]
          [else (fn ks kvs (cons (car xs) vs) (cdr xs))]))
  (fn '[] '[] '[] xs))

(def (func-args func args)
  (apply keyword-apply func (parse-args args)))

And now I can do
:
(def (suma a b #:c [c 0]) (+ a b c))
(func-args suma (list 1 2 #:c 3))

and it works fine.

Thanks again!

Dimaugh Silvestris

unread,
Nov 28, 2020, 8:49:25 AM11/28/20
to Racket Users
Just in case somebody has a similar issue and finds this:
In the end I used keyword-apply/sort , which doesn't requiere keywords to follow the same order they do in the function definition.
Reply all
Reply to author
Forward
0 new messages