Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure equivalent in Racket: (map #(procedure) (list))

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?

like image 864
Theodor Berza Avatar asked Aug 24 '26 12:08

Theodor Berza


2 Answers

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.

like image 100
Alexis King Avatar answered Aug 27 '26 03:08

Alexis King


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

like image 34
MicSokoli Avatar answered Aug 27 '26 04:08

MicSokoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!