On Thursday, 8 July 2021 16:37:09 CEST you wrote:
> Hi,
>
> I'm seeking advice for passing simple key-value pairs to a function and
> generate a string out of these values. Neither the names not the number
> of keys is known in advance.
>
> Background: This shall become a generic function for generating URI
> query-strings.
>
> My current approach please see below. Anyhow, I'm wondering whether the
> quite and quasiquote can be replaced by something simpler.
>
> (use-modules (ice-9 match))
>
> (define limit 100)
> (define evaluation "linux")
>
> (define* (api-uri base path #:rest query)
>
>    (define (build-query-string kv)
>      (match kv
>         ((name #f) #f)
>         ((name (? string? value))
>          (string-append name "=" value))  ; FIXME: encode
>         ((name (? number? value))
>          (string-append name "=" (number->string value)))))
>
>
>    (format #t "~%Query: ~a~%~%" query)
>    (let ((query-string
>       (when query
>         (string-join
>          (filter (lambda (x) x) (map build-query-string query))
>          "&"))))
>      (format #t "~%Query-String: ~a~%~%" query-string)
>      ;; todo: build uri incl. query-string
>    ))
>
>
> (api-uri "https://ci.guix.gnu.org"; "/api/jobs")
> (api-uri "https://ci.guix.gnu.org"; "/api/jobs"
>       `("nr" ,limit)
>       `("evaluation" ,evaluation)
>       `("system" ,#f))

Hello,

personally I'd use key-value pairs rather than lists for passing in arguments
and simplify it a bit by using fold-right from SRFI-1, like this:

#+BEGIN_SRC scheme
(use-modules (srfi srfi-1))

(define (api-uri base path . query)
  (string-join
   (fold-right
        (lambda (name-value-pair result)
          (if (cdr name-value-pair)
                  (cons (string-append (car name-value-pair)
                                                           "="

(object->string (cdr name-value-pair)))
                                 result)
                  result))
        '()
        query)
   "&"))

(api-uri "https://ci.guix.gnu.org";
                 "/api/jobs"
                 (cons "nr" limit)
                 (cons "evaluation" evaluation)
                 (cons "system" #f))
#+END_SRC

Vale,

-Tim



Reply via email to