why does
(floor 4.5)
return 4 and 0.5 but
floor
gives an error:
The variable FLOOR is unbound.
[Condition of type UNBOUND-VARIABLE]
Note: I come from a clojure background
How would I be able to access the actual floor procedure?
if you use parentheses, like in your first example: (floor ...) Common Lisp recognizes it as a list and because it's unquoted, it evaluates it. The first form in an evaluated list must be a function name, a macro name or a special form.
In your second example, you did not use parentheses, so it is not treated as a list, therefore CL tries to interpret it as a variable (variables and functions are in different namespaces).
Try typing (floor), you'll get different error message (invalid number of arguments).
You can access the function namespace by typing
#'floor
or
(function floor)
(these are essentially the same).
#'floor
Common Lisp keeps variables and functions in different namespaces.
Related
I'm looking for the technical answer answer here. How is Clojure interpreting these symbols? My current working understanding is that the opening paren '(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated (whether function or value).
Any and all details on the truth here would be appreciated. I'm looking to go deep here as well as seeing/knowing every level of abstraction along the way. It bugs me to know that I may have some imaginal thinking going on currently.
(foo x1 x2)
is the syntax for calling a special form or var (function or macro).
So the compiler will analyze the form (foo x1 x2) and will check if foo is a special form (if, try, let*, etc.) and if not, the symbol will be resolved to a var in the context of the current namespace. If that var is macro, then macroexpansion will happen, else the call will be treated as a normal function call.
To prevent treating (foo x1 x2) as a function call you can quote the expression: '(foo x1 x2) and then it will just remain a list of symbols.
More info:
https://clojure.org/reference/special_forms
https://clojure.org/reference/macros
You are trying to do too much at once when you say
'(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated
The Clojure evaluation model does not assign semantics to characters directly. Instead, evaluation of a Clojure program goes through two broad phases:
First, read the characters in the source file according to the language's lexical rules, yielding a Clojure data structure
Second, evaluate that data structure, according to the language's evaluation rules, yielding a value
So when we write an expression like (+ (* 4 5) 2), what happens? The reader matches up parentheses to create lists, and yields as its result a list of three elements: the symbol +, another list (containing the symbol * and the numbers 4 and 5), and the number 2.
Next we move to evaluate that expression. Notice, crucially, that at this point there is no trace of parentheses. The textual source of the program is no longer material. We're evaluating a list. Of course, if we printed that list, conventionally we would surround it with parentheses, but that does not concern the evaluator. How do we evaluate this list? Well, the evaluation rule for lists is to, first, evaluate each of the components, and then invoke the first component as a function, passing the remaining components as arguments1. So our list of pending tasks is:
Evaluate +
Evaluate (* 4 5)
Evaluate 2
Invoke the result of (1), passing the results of (2) and (3) as arguments
(1), of course, evaluates to the addition function, (2) evaluates (in a similar manner) to the number 20, and (3) evaluates to the number 2 (since numbers evaluate to themselves). Thus, (4) becomes "Invoke the addition function, passing the numbers 20 and 2 as arguments". Of course, the final result is 22.
1 The rule is actually more complicated than this, because of macros, but for functions this suffices.
The other 2 answers are great. The simple summary is:
foo( x1, x2 ) // Java function call
(foo x1 x2) // Clojure function call
In both cases, the compiler will evaluate any nested function calls in x1 or x2 before calling foo on the resulting values.
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!
%% Function even_print(List),takes a list and returns a list of only even numbers. Function even_odd(X), takes an integer and tells if it is even or odd.
even_print(List) ->
[X||X<-List, even<-even_odd(X)].
I don't understand why I get this error:
3> seq_erlang:even_print([2,3,4]).
** exception error: no function clause matching
seq_erlang:'-even_print2/1-lc$^1/1-1-'(even) (seq_erlang.erl, line 154)
Just to comment, I have already implemented another function that prints even numbers just fine (so please don't comment with other implementations). I need help with this one only.
That should be even == even_odd(X) instead of using <-. A list comprehension has two types of "clauses": those that map over a list with <-, and those that filter out undesired combinations using a guard or boolean expression that doesn't contain <-.
(And a third one: extract bytes from a binary using <=; but that one is more rarely used.)
I simply want to pass a list of integers to a function written in C++. I've set up the template (.tm) file and all, and I can successfully call a test function whith scalar arguments. Calling the function with the list argument behaves as though the function was not defined at all. I suspect that the argument types don't match.
In the documentation for templates (http://reference.wolfram.com/mathematica/ref/file/file.tm.html) the datatype for lists is something like "Int32List". When I use that, my C++ function must contain an extra long parameter for the list length. The only example code which uses a list is "sumalist.tm". This example uses IntegerList (a type which doesn't appear in the doku).
When I use Int32List, the mprep result requires a function with an extra integer argument (not long as written in the doku). When I use the undocumented IntegerList type, the extra argument is of type long.
During my experiments with scalar types, I had a similar problem - a c++ function was called properly when using "Integer" in the tm-file, and not recognized with "Integer32".
The "sumalist.tm" example also uses a strange Pattern (list:{___Integer}) about which I didn't find any documentation. I'd also like to understand what the Evaluate line means (I suspect that it's used make the function callable without the curly braces around the list).
So who know which datatypes are really appropriate to call a c++ function with a list - maybe also with reals... ?
The mapping of MathLink data types (e.g., Integer32, Integer32List, ...) to C/C++ types is described on the MathLink template file documentation page.
The page no longer documents the old interface types Integer, Real, IntegerList and RealList. These should no longer be used, because the mapping of these types depends on C types whose bit length is platform and compiler dependent (e.g., long). Use the corresponding new type with explicit bit length instead (i.e., Integer32 or Integer64 instead of Integer). The old interface types are still documented in the somewhat dated MathLink reference guide.
The following talk slides contain a simple MathLink example that shows how to implement a MathLink function that adds a scalar value to a vector of reals. This may serve as a starting point.
I don't know much about MathLink, but I can explain the pattern, list:{___Integer}.
The colon is just the general form for a named pattern, that is symbol:pattern just says that the object referred to by symbol has to match pattern. Indeed, pattern like a_Integer or b__List are really just short forms for a:_Integer and b:__List.
So what we are left with interpreting is {___Integer}. This is a pattern matching a list of arbitrary many (including zero) integers. It works as follows:
{Pattern} is the Pattern for a list whose contents matches Pattern
___Integer is the Pattern for a sequence of zero or more Integers.
What are the best practices for defining constants in Clojure in terms of style, conventions, efficiency, etc.
For example, is this right?
(def *PI* 3.14)
Questions:
Should constants be capitalized in Clojure?
Stylistically, should they have the asterisk (*) character on one or both sides?
Any computational efficiency considerations I should be aware of?
I don't think there is any hard and fast rules. I usually don't give them any special treatment at all. In a functional language, there is less of a distinction between a constant and any other value, because things are more often pure.
The asterisks on both sides are called "ear muffs" in Clojure. They are usually used to indicate a "special" var, or a var that will be dynamically rebound using binding later. Stuff like out and in which are occasionally rebound to different streams by users and such are examples.
Personally, I would just name it pi. I don't think I've ever seen people give constants special names in Clojure.
EDIT: Mister Carper just pointed out that he himself capitalizes constants in his code because it's a convention in other languages. I guess this goes to show that there are at least some people who do that.
I did a quick glance through the coding standards but didn't find anything about it. This leads me to conclude that it's really up to you whether or not you capitalize them. I don't think anyone will slap you for it in the long run.
On the computational efficiency front you should know there is no such thing as a global constant in Clojure. What you have above is a var, and every time you reference it, it does a lookup. Even if you don't put earmuffs on it, vars can always be rebound, so the value could always change, so they are always looked up in a table. For performance critical loops this is most decidedly non-optimal.
There are some options like putting a let block around your critical loops and let the value of any "constant" vars so that they are not looked up. Or creating a no-arg macro so that the constant value is compiled into the code. Or you could create a Java class with a static member.
See this post, and the following discussion about constants for more info:
http://groups.google.com/group/clojure/msg/78abddaee41c1227
The earmuffs are a way of denoting that a given symbol will have its own thread-local binding at some point. As such, it does not make sense to apply the earmuffs to your Pi constant.
*clojure-version* is an example of a constant in Clojure, and it's entirely in lower-case.
Don't use a special notation for constants; everything is assumed a constant unless specified otherwise.
See http://dev.clojure.org/display/community/Library+Coding+Standards
Clojure has a variety of literals such as:
3.14159
:point
{:x 0
:y 1}
[1 2 3 4]
#{:a :b :c}
The literals are constant. As far as I know, there is no way to define new literals. If you want to use a new constant, you can effectively generate a literal in the code at compile-time:
(defmacro *PI* [] 3.14159265358979323)
(prn (*PI*))
In Common Lisp, there's a convention of naming constants with plus signs (+my-constant+), and in Scheme, by prefixing with a dollar sign ($my-constant); see this page. Any such convention conflicts with the official Clojure coding standards, linked in other answers, but maybe it would be reasonable to want to distinguish regular vars from those defined with the :const attribute.
I think there's an advantage to giving non-function variables of any kind some sort of distinguishing feature. Suppose that aside from variables defined to hold functions, you typically only use local names defined by function parameters, let, etc. If you nevertheless occasionally define a non-function variable using def, then when its name appears in a function definition in the same file, it looks to the eye like a local variable. If the function is complex, you may spend several seconds looking for the name definition within the function. Adding a distinguishing feature like earmuffs or plus signs or all uppercase, as appropriate to the variable's use, makes it obvious that the variable's definition is somewhere else.
In addition, there are good reasons to give special constants like pi a special name, so no one has to wonder whether pi means, say, "print-index", or the i-th pizza, or "preserved interface". Of course I think those variables should have more informative names, but lots of people use cryptic, short variable names, and I end up reading their code. I shouldn't have to wonder whether pi means pi, so something like PI might make sense. None would think that's a run of the mill variable in Clojure.
According to the "Practical Clojure" book, it should be named *pi*