Executing multiple statements in if-else without nullpointer exception

大憨熊 提交于 2019-12-18 13:52:46

问题


I'm trying to dig a little deeper into clojure and functional programming.

At some point of my code I have a (def server (spawn-server)). Now I want a short function for the REPL to check the state of this socket.

This is what I have at the moment:

(defn status []
  (if server 
    (
      (println "server is up and running")
      (println "connections:" (connection-count server)) 
     )    
    (println "server is down")))

If server is nil, everything works fine, but this is the output on the REPL if the server is running:

=> (status)
server is up and running
connections: 0
#<CompilerException java.lang.NullPointerException (NO_SOURCE_FILE:0)>

I'm not really sure if I see the problem, but I can't figure out how this should work :-) What I have here is this:

((println "foo")(println "foo"))

which will be evaluated to (nil nil) which results in the NullPointerException ?

Usally I wouldn't use the outer parentheses but how can I create some kind of "block" statement for the if-condition. If I don't use them, the second println will be used as else.

What would work is the usage of let as some kind of "block"-statement:

(let [] 
  (println "server is up and running"),
  (println "connections:" (connection-count server)) )

But I'm not really sure if this the "right" solution?


回答1:


Use do:

(defn status []
  (if server 
    (do
      (println "server is up and running")
      (println "connections:" (connection-count server)))    
    (println "server is down")))

In Lisps, generally, you can't just add parens for grouping.

((println "foo") (println "foo"))

Here, the return value of the first (println "foo") will be tried to be called (as a function), with the return value of the second as an argument. Those are very basic evaluation rules, so I suggest that you hit some introductory books or documentation about Clojure or Lisps in general.

From the evaluation section of the Clojure homepage:

Non-empty Lists are considered calls to either special forms, macros, or functions. A call has the form (operator operands*).

Macros or special forms may "break" this rule.



来源:https://stackoverflow.com/questions/6234018/executing-multiple-statements-in-if-else-without-nullpointer-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!