Threading functions

Is there a simpler way to achieve threading functionality in racket? I know about the threading library but it seems like such a basic functionality that I wonder if there is not some builtin way to do this.

(define (thread x . fns)
    (foldl (lambda (f a) (f a))

Also, can you express (lambda (f a) (f a)) in a simpler fashion?

1 answer

  • answered 2020-02-13 00:33 tfb

    There are lots of ways of doing this. A nice one is to use a macro, a simple (and perhaps not completely correct) version of which is:

    (define-syntax (/> stx)
      (syntax-case stx ()
        [(_ x)
        [(_ x f)
         #'(f x)]
        [(/> x f fs ...)
         #'(/> (f x) fs ...)]
         (identifier? #'/>)
         #'(λ (x . fns)
             (for/fold ([r x]) ([f fns])
               (f r)))]))

    Now, for instance (/> x sin cos) is expanded to (cos (sin x)): there is no run-time overhead at all. The last clause means that (apply /> 1 (list sin cos)) will work.

    I'm not sure the above macro is completely correct, particularly the last clause.