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

前端 未结 2 812
轻奢々
轻奢々 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.

提交回复
热议问题