r/Clojure • u/eatme_23 • Feb 03 '23
[Q&A] Noob has simple program problem.
I wanted to write a program to add 2 to a list of numbers then sum the list and print the result. So '(5 7) would yield 16. I posted my version to s Clojure board and received a number of different replies. In retrospect I didn't fully explain the problem to them.
10
u/andyjda Feb 03 '23
What have you tried and what issue are you having?
4
u/dalanicolai Feb 03 '23
@u/eatme_23 And what is Clojure board? If possible, you should add a link to your question/solution...
1
1
u/eatme_23 Feb 04 '23
I would like to thank everyone who contributed it was most interesting and informative what people had to say. I'm not clear about the usage of # and %. I have consulted The Clojure Cheatsheet and the intro to Clojure webpage. Neither included % and the usage of # shed no light. I won't bother anyone regarding the above but I did stumble across an interesting speed optimization. https://clojureverse.org/t/my-recent-clojure-vs-c-experience/6909
3
u/Save-Lisp Feb 04 '23 edited Feb 04 '23
The symbol # is shorthand for defining a function. % is the symbol used to access the arguments in the function. It's used to write small functions typically to pass to other generic higher order functions like map or reduce.
(map (fn [x] (+ 2 x)) [5 7])is equivalent to(map #(+ 2 %) [5 7])You can see how it works under the hood using
macroexpand-1. Try(macroexpand-1 '#(+ 2 %))in a REPL.1
u/eatme_23 Feb 05 '23
Thank you for your generous assistance. I get it now. Hmm, I tried nacroexpand-1,,, in my trusty Android 9 Code Editor and it returned null. Even without the SQUOTE. It uses Clojure 1.10.1 if that matters. Code Editor is pretty cool. I've used Swift, Kotlin, Pascal and JavaScript as well. Bugs me no end that I can't access local files. Must need to root the stupid thing.
1
u/kawas44 Feb 04 '23
On the Clojure website, "Reference" section: https://clojure.org/reference/other_functions
The table's second line show the
reader macroto define a function and you have a link to read thereader macrodocumentation. Look forDispatch (#)chapter.1
u/eatme_23 Feb 05 '23
I'm so impressed with the helpful and useful replies to people of written on this sub. Thank you for the link.
4
u/slashkehrin Feb 03 '23
I'd do something like this:
(defn foo [numbers]
(reduce + (map #(+ % 2) numbers)))3
4
1
u/Zimtt Feb 03 '23
If ur a beginner in programming: maybe try something else. The documentation for clojure is rly not for beginners
6
u/exahexa Feb 03 '23
You can use
mapto add 2 to every element and thanreducewith + orapplywith +