How to read mentally Lisp/Clojure code

后端 未结 3 519
攒了一身酷
攒了一身酷 2021-01-29 17:41

Thanks a lot for all the beautiful answers! Cannot mark just one as correct

Note: Already a wiki

I am new to functional programming and while

3条回答
  •  不要未来只要你来
    2021-01-29 18:23

    First remember that functional program consists of expressions, not statements. For example, form (if condition expr1 expr2) takes its 1st arg as a condition to test for the boolean falue, evaluates it, and if it eval'ed to true then it evaluates and returns expr1, otherwise evaluates and returns expr2. When every form returns an expression some of usual syntax constructs like THEN or ELSE keywords may just disappear. Note that here if itself evaluates to an expression as well.

    Now about the evaluation: In Clojure (and other Lisps) most forms you encounter are function calls of the form (f a1 a2 ...), where all arguments to f are evaluated before actual function call; but forms can be also macros or special forms which don't evaluate some (or all) of its arguments. If in doubt, consult the documentation (doc f) or just check in REPL:

    user=> apply
    #
    a function
    user=> doseq
    java.lang.Exception: Can't take value of a macro: #'clojure.core/doseq
    a macro.

    These two rules:

    • we have expressions, not statements
    • evaluation of a subform may occur or not, depending of how outer form behaves

    should ease your groking of Lisp programs, esp. if they have nice indentation like the example you gave.

    Hope this helps.

提交回复
热议问题