eengebruiker
eengebruiker

Reputation: 27

Avoiding output clojure function

When I use for example a small function like (defn ll [] (load-file "D:\\Work.clj")) It will always return a value. In this case nil.

Sometimes a function is only appreciated for its side-effect, here loading the clojure file. So no return-value is needed. In the file to load, the last line says. (println "\n-- K:\\Work.clj loaded --") This is what I want to see and a nil in the repl after this, seems ugly to me.

(I have this idea from AutoCAD/AutoLisp. When you write a function like so (defun abcd () . . . some action here . . . (princ)) it will not return any value. BTW: AutoLISP is not implemented in a functional way.)

Avoiding output does not fit the functional way of thinking. I understand that but sometimes you don't want a function, you want to do something. Also see Using Clojure in Repl without opening en closing parentheses

Upvotes: 0

Views: 835

Answers (2)

leetwinski
leetwinski

Reputation: 17859

returning some value from any expression is one of the definitive features of the lisp family languages (functional or not).

My guess is that autolisp also can't have 'void' return.

and indeed, the wikipedia article on autolisp says the following here:

Note the final line inside the function definition: when evaluated with no arguments, the princ function returns a null symbol, which is not displayed by the AutoCAD command-line interface.

so, your question deals mainly with the print function specification + repl behaviour, rather than with language semantics.

as of clojure, all the repls i'm aware of, print out any value returned, including null characters and empty strings. And that looks consistent.

strictly speaking, there is one way to make expression non returning in clojure: make it infinitely recursive.. but well..

irrelevant addition

just to illustrate the logic and symmetry: in common lisp you can write a function, returning 'nothing':

CL-USER> (defun f ()
           (values))

CL-USER> (f)
; No values

but again, if you actually 'use' the result of f, it is nil:

CL-USER> (list (f))
;;=> (NIL)

this form of return is there for developers, who want to emphasize that the return value of the function is irrelevant.

Upvotes: 2

Alan Thompson
Alan Thompson

Reputation: 29958

Every expression in Clojure (not just functions!) returns a value. This cannot be changed. Functions intended for side effects typically return nil as a placeholder or "dummy" return value. Examples include both doseq and print. So something like (println "hello") has the side-effect of sending characters to the output device (i.e. stdout), then returns the dummy value nil.

Upvotes: 2

Related Questions