Why is the return value of a function not evaluated but the return value of a macro is? - clojure

A function to add one and one:
(defn one-plus-one [] (list + 1 1))
when called returns:
(#object[clojure.core$_PLUS_ 0x47fa7bd5 "clojure.core$_PLUS_#47fa7bd5"] 1 1)
The same function body wrapped in a macro:
(defmacro one-plus-one [] (list + 1 1))
when called returns:
2
Why does Clojure expect macros to return expressions that can be evaluated?
Edit
The answers to the possible duplicate question tells how a macro is different from a function. But does not answer the why. Metaphorically, I know that an object left from an altitude drops vertically to hit the ground. My question is why does it drop vertically?

Let's just start with one thing many people know so well they forget to think about it explicitly when explaining macros, which causes others to be confused when learning to think about macros:
-----------> macros are functions <-------------
They are very often used to take lists of things that look like code, and are very often expected to return lists that can actually be run as code.
The difference between a macro and a function is not what it does (fundamentally), but when it does it. macros run while the code is "loading" and the value they return is run when the program runs.
when you write it as a macro it does two steps:
run the function to produce a list
run that returned list as code to produce a value
when you write it as a function it does one step:
run the function to produce a list
Then it stops.
The return value is diferent because the macro version takes that extra step of running the returned value as code.
code is data ... data is code ... yay lisp!

Related

If... else condition in LUA language

I'm new to coding and I recently started to take my baby steps in LUA. I have a small problem so it would be very helpful if you can help me. In my code, I need to code that
If x ~= 1 and x~=2 and x~=3 and x~=4 then (do something) end
is there a faster way not to hardcode that part, not to type the whole thing from x~=1 to x~=4?
Thank you!
If you need something like if x ~= 1 and x~=2 and x~=3 and x~=4 then (do something) end x is usually an integer.
Then
if x < 1 or x > 4 then
-- do your stuff here
end
Is what you are looking for. If you want to explicitly check wether x is unquald 1,2,3,4 you can simply do something like Egor suggested.
But as you see unless you can describe your conditions in a shorter mathematical way you still have separate unique conditions and you won't come around writing them down.
If you have to check those conditions repeatedly you can use a truth table like in Egor's example or you write a function that returns if that condition is met for its argument.

Clojure creating higher order first function

; Now create a function that takes a function (which produces a sequence)
; as an argument. Your function should invoke that function and return and
; return the first element from the returned sequence.
(is (higher-order-first-function? __))
Guys it is actually a part of my homework. I have 1000 lines of codes to do. This is just a part that i could not figure out how to do it. Can anyone help me how to solve this ? I tried every possible way but. I could not pass the testing.
So the steps are pretty clear from the comments:
Write a function that expects one parameter (use defn, fn, or #())
That parameter should be a function, so check for that (fn?)
Call that function
Return the first element in the returned sequence (first)

Lazy evaluation of expression in Elixir

I'm trying to figure out if there is a macro similar to delay in clojure to get a lazy expression/ variable that can be evaluated later.
The use case is a default value for Map.get/3, since the default value comes from a database call, I'd prefer it to be called only when it's needed.
Elixir's macro could be used for writing simple wrapper function for conditional evaluation. I've put one gist in the following, though it may be better/smarter way.
https://gist.github.com/parroty/98a68f2e8a735434bd60
"Generic" laziness is a bit of a tough nut to crack because it's a fairly broad question. Streams allow laziness for enumerables but I'm not sure what laziness for an expression would mean. For example what would a lazy form of x = 1 + 2 be? When would it be evaluated?
The thought that comes to mind for a lazy form of an expression is a procedure expression:
def x, do: 1 + 2
Because the value of x wouldn't be calculated until the expression is actually invoked (as far as I know). I'm sure others will correct me if I'm wrong on that point. But I don't think that's what you want.
Maybe you want to rephrase your question--leaving out streams and lazy evaluation of enumerated values.
One way to do this would be using processes. For example the map could be wrapped in a process like a GenServer or an Agent where the default value will be evaluated lazy.
The default value can be a function which makes the expensive call. If Map.get/3 isn't being used to return functions you can check if the value is a function and invoke it if it is returned. Like so:
def default_value()
expensive_db_call()
end
def get_something(dict, key) do
case Map.get(dict, key, default_value) do
value when is_fun(value) ->
value.() # invoke the default function and return the result of the call
value ->
value # key must have existed, return value
end
end
Of course if the map contains functions this type of solution probably won't work.
Also check Elixir's Stream module. While I don't know that it would help solve your particular problem it does allow for lazy evaluation. From the documentation:
Streams are composable, lazy enumerables. Any enumerable that generates items one by one during enumeration is called a stream. For example, Elixir’s Range is a stream:
More information is available in the Stream documentation.
Map.get_lazy and Keyword.get_lazy hold off on generating the default until needed, links the documentation below
https://hexdocs.pm/elixir/Map.html#get_lazy/3
https://hexdocs.pm/elixir/Keyword.html#get_lazy/3
You can wrap it in an anonymous function, then it will be evaluated when the function is called:
iex()> lazy = fn -> :os.list_env_vars() end
#Function<45.79398840/0 in :erl_eval.expr/5>
iex()> lazy.()

can defmacro quota parameter in clojure?

I have a string which will evaluate to true or false, can I use macro and pass the string as parameter? I write the following, but the result is string of (= 0 0) instead of true. How to get true result?
(def a "(= 0 0)")
(defmacro test [code-string] code-string)
(test a)
update:
The purpose is replace dynamic SQL. Currently we store code like 'column_a > 1' in database, and then we will get the code, and assemble a sql like
select case when column_a>1 then 0 else 1 end as result from table
There are many such code, and I hope to use clojure run in parallel to speed it up. To use clojure I could store '(> row["column_a"] 1)' in database, and then in jdbc looping, call (> row["column_a"] 1) to do my logic, like storing some code section in database and need to run it.
As TaylanUB already said, Clojure provides eval to evaluate some expression at run-time. However, using eval is frowned upon unless you have very good reasons to use it. It's not clear what you're really intending to do, so it would be helpful to provide a more real world example. If you don't have one, you don't need eval.
Similarly, macros are used to transform code and are not run at run-time, instead the code to which the macro evaluates gets run. The typical approach would be to try to solve a problem with a mere function, only if a macro would buy you something in terms of applicability to a wider range of code, consider turning the code into a macro. Edit: take a look at some introduction to macros in Clojure, e.g. this part from Clojure from the ground up
No, you cannot directly use a string as code. Defmacro takes s-expressions not strings. Clojure might have something like read which can parse a string and make an s-expression out of it which you might then be able to execute as code via something like eval.
There is usually no good reason to put code in strings or other data structures which will exist during program execution anyway, try to just work with first-class functions instead. Or mention the precise problem you're trying to solve and people might be able to give better answers. This might be an instance of the XY problem.
Note: I don't know Clojure, but all of this is pretty Lisp-generic.
(defn eval-code [code-string]
(eval (read-string code-string)))
(eval-code "(= 0 0)")
;; you don't need macro here.

How can I avoid using the stack with continuation-passing style?

For my diploma thesis I chose to implement the task of the ICFP 2004 contest.
The task--as I translated it to myself--is to write a compiler which translates a high-level ant-language into a low-level ant-assembly. In my case this means using a DSL written in Clojure (a Lisp dialect) as the high-level ant-language to produce ant-assembly.
UPDATE:
The ant-assembly has several restrictions: there are no assembly-instructions for calling functions (that is, I can't write CALL function1, param1), nor returning from functions, nor pushing return addresses onto a stack. Also, there is no stack at all (for passing parameters), nor any heap, or any kind of memory. The only thing I have is a GOTO/JUMP instruction.
Actually, the ant-assembly is for to describe the transitions of a state machine (=the ants' "brain"). For "function calls" (=state transitions) all I have is a JUMP/GOTO.
While not having anything like a stack, heap or a proper CALL instruction, I still would like to be able to call functions in the ant-assembly (by JUMPing to certain labels).
At several places I read that transforming my Clojure DSL function calls into continuation-passing style (CPS) I can avoid using the stack[1], and I can translate my ant-assembly function calls into plain JUMPs (or GOTOs). Which is exactly what I need, because in the ant-assembly I have no stack at all, only a GOTO instruction.
My problem is that after an ant-assembly function has finished, I have no way to tell the interpreter (which interprets the ant-assembly instructions) where to continue. Maybe an example helps:
The high-level Clojure DSL:
(defn search-for-food [cont]
(sense-food-here? ; a conditional w/ 2 branches
(pickup-food ; true branch, food was found
(go-home ; ***
(drop-food
(search-for-food cont))))
(move ; false branch, continue searching
(search-for-food cont))))
(defn run-away-from-enemy [cont]
(sense-enemy-here? ; a conditional w/ 2 branches
(go-home ; ***
(call-help-from-others cont))
(search-for-food cont)))
(defn go-home [cont]
(turn-backwards
; don't bother that this "while" is not in CPS now
(while (not (sense-home-here?))
(move)))
(cont))
The ant-assembly I'd like to produce from the go-home function is:
FUNCTION-GO-HOME:
turn left nextline
turn left nextline
turn left nextline ; now we turned backwards
SENSE-HOME:
sense here home WE-ARE-AT-HOME CONTINUE-MOVING
CONTINUE-MOVING:
move SENSE-HOME
WE-ARE-AT-HOME:
JUMP ???
FUNCTION-DROP-FOOD:
...
FUNCTION-CALL-HELP-FROM-OTHERS:
...
The syntax for the ant-asm instructions above:
turn direction which-line-to-jump
sense direction what jump-if-true jump-if-false
move which-line-to-jump
My problem is that I fail to find out what to write to the last line in the assembly (JUMP ???). Because--as you can see in the example--go-home can be invoked with two different continuations:
(go-home
(drop-food))
and
(go-home
(call-help-from-others))
After go-home has finished I'd like to call either drop-food or call-help-from-others. In assembly: after I arrived at home (=the WE-ARE-AT-HOME label) I'd like to jump either to the label FUNCTION-DROP-FOOD or to the FUNCTION-CALL-HELP-FROM-OTHERS.
How could I do that without a stack, without PUSHing the address of the next instruction (=FUNCTION-DROP-FOOD / FUNCTION-CALL-HELP-FROM-OTHERS) to the stack? My problem is that I don't understand how continuation-passing style (=no stack, only a GOTO/JUMP) could help me solving this problem.
(I can try to explain this again if the things above are incomprehensible.)
And huge thanks in advance for your help!
--
[1] "interpreting it requires no control stack or other unbounded temporary storage". Steele: Rabbit: a compiler for Scheme.
Yes, you've provided the precise motivation for continuation-passing style.
It looks like you've partially translated your code into continuation-passing-style, but not completely.
I would advise you to take a look at PLAI, but I can show you a bit of how your function would be transformed, assuming I can guess at clojure syntax, and mix in scheme's lambda.
(defn search-for-food [cont]
(sense-food-here? ; a conditional w/ 2 branches
(search-for-food
(lambda (r)
(drop-food r
(lambda (s)
(go-home s cont)))))
(search-for-food
(lambda (r)
(move r cont)))))
I'm a bit confused by the fact that you're searching for food whether or not you sense food here, and I find myself suspicious that either this is weird half-translated code, or just doesn't mean exactly what you think it means.
Hope this helps!
And really: go take a look at PLAI. The CPS transform is covered in good detail there, though there's a bunch of stuff for you to read first.
Your ant assembly language is not even Turing-complete. You said it has no memory, so how are you supposed to allocate the environments for your function calls? You can at most get it to accept regular languages and simulate finite automata: anything more complex requires memory. To be Turing-complete you'll need what amounts to a garbage-collected heap. To do everything you need to do to evaluate CPS terms you'll also need an indirect GOTO primitive. Function calls in CPS are basically (possibly indirect) GOTOs that provide parameter passing, and the parameters you pass require memory.
Clearly, your two basic options are to inline everything, with no "external" procedures (for extra credit look up the original meaning of "internal" and "external" here), or somehow "remember" where you need to go on "return" from a procedure "call" (where the return point does not necessarily need to fall in the physical locations immediately following the "calling" point). Basically, the return point identifier can be a code address, an index into a branch table, or even a character symbol -- it just needs to identify the return target relative to the called procedure.
The most obvious here would be to track, in your compiler, all of the return targets for a given call target, then, at the end of the called procedure, build a branch table (or branch ladder) to select from one of the several possible return targets. (In most cases there are only a handful of possible return targets, though for commonly used procedures there could be hundreds or thousands.) Then, at the call point, the caller needs to load a parameter with the index of its return point relative to the called procedure.
Obviously, if the callee in turn calls another procedure, the first return point identifier must be preserved somehow.
Continuation passing is, after all, just a more generalized form of a return address.
You might be interested in Andrew Appel's book Compiling with Continuations.