I have this Clojure code:
(def target-data
(map #(vector % (+ (* % %) % 1))
(range -1.0 1.0 0.1)))
How do I translate it in Racket? I tried:
(define (target-data)
(map #(vector % (+ (* % %) % 1))
(range -1.0 1.0 0.1)))
The # which appears to be a reader macro in Clojure doesn't have its equivalent in Racket. How do I create it?
As mentioned, the #(...) form in Clojure is just a shorthand syntax for (fn ...), which is called (lambda ...) in Racket. If you want it to be shorter, you can also use (λ ...), and DrRacket actually has a shortcut for inserting the λ character.
Using λ, your code would look like this:
(define (target-data)
(map (λ (x) (vector x (+ (* x x) x 1)))
(range -1.0 1.0 0.1)))
If you want Clojure-like shorthand, #lang racket does not support anything like that out of the box, but Racket is flexible enough to add it as a reader macro. There are a couple different packages that implement Clojure-like function shorthand, including one I have written called curly-fn, which is very similar to the Clojure shorthand.
To use it, first install the curly-fn package:
raco pkg install curly-fn
Then add curly-fn as a “meta language” at the top of your file:
#lang curly-fn racket
This will extend the racket language with the function shorthand, which looks like this:
#{vector % (+ (* % %) % 1)}
Notably, it is nearly identical to the Clojure syntax, but since #(...) is already used in Racket for vector literals, curly-fn uses #{...} instead. Therefore, your program would look like this:
(define (target-data)
(map #{vector % (+ (* % %) % 1)}
(range -1.0 1.0 0.1)))
Since curly-fn is a meta-language, it can also be used with any other language that uses s-expression syntax, such as #lang curly-fn racket/base or even #lang curly-fn typed/racket.
The curly-fn shorthand is also a little bit more flexible than the Clojure equivalent—notably, it can also be used as a simple shorthand for curry if no arguments are used—and you can find all the details in the package documentation.
You might be looking for lambdas.
(define target-data
(map (lambda (x) (vector x (+ (* x x) x 1)))
(range -1.0 1.0 0.1)))
This seems to give the same result for me as the Clojure code.
https://docs.racket-lang.org/guide/lambda.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With