Generating a symbol from a string and applying it as a function

前端 未结 2 808
轻奢々
轻奢々 2021-01-28 17:57

I\'m just learning clojure, and I\'m hitting a wall.

I\'m trying to read an arithmetic expression as an infix string and process it in Clojure.

e.g. \"1 + 2\" ->

相关标签:
2条回答
  • 2021-01-28 18:19

    What's your reason to write such code? If you want to have function called plus which gonna be + synonym just write (def plus +).

    Clojure + is normal function. You can use it like (+ 1 2 3 4 5). There's no reason to turn it into symbol.

    Clojure have no operators at all. Only functions and macros.

    Still, if you insist on using symbol you need to eval it like so

    (def plus (eval (symbol "clojure.core/+"))).

    Have a look on class of (symbol "clojure.core/+") and + itself.

    (class (symbol "clojure.core/+")) ;;clojure.lang.Symbol

    (class +) ;;clojure.core$_PLUS_

    Symbols themselves are not callable as functions which are "under this symbols". If you want to "turn symbol into callable function" you have to eval it.

    0 讨论(0)
  • 2021-01-28 18:22

    Symbols have a function attached to them by default. The function that is attached to them by default is look this key up in a map. That is why your plus behaves oddly. It is attempting to look up elements in a map.

    (plus 1 1) This is really look the symbol + up in the map 1 and if not found return a default value of 1.

    (plus 1 2) Same as above except default value is 2.

    clojure docs for symbols

    0 讨论(0)
提交回复
热议问题