There are some math functions that end with apostrophe like: +', *', and -'.
What is the difference between non-apostrophe and apostrophe ones?
They are the "auto-promoting" versions of the normal math functions.
user> (* Long/MAX_VALUE 2)
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)
user> (*' Long/MAX_VALUE 2)
18446744073709551614N
They will return a larger data-type than the input if the output gets too big.
This used to be the default behaviour early in Clojure, and then it was changed to throw an exception if the output of a math operation overflowed it's data type. This improved numeric performance and generally helped find bugs. In the five or so years since then surprisingly few people have complained about this change breaking anything. It was decided to keep the behaviour of throwing an exception on overflow because this is almost always a bug.
In practice, most of the time you will know when you are going to need to use BigIntegers and BigDecimals and can use the normal functions with these data types.
user> (* Long/MAX_VALUE 2N)
18446744073709551614N
In this example I used the normal * function, and passed it an argument that was of type BigInteger (that's what the N in 2N means to the clojure-reader)
There are a few cases where you really need to work with any size number without knowing it's size in advance and these functions come in handy. So far most of these examples for me are factorial examples on StackOverflow.
If you really want your math operation to overflow then you can use the explicitly unsafe math functions:
user> (unchecked-add Long/MAX_VALUE 2)
-9223372036854775807
Related
So, in weakly-typed C, 0 is evaluated as false in a boolean context (like a conditional expression) and everything else is truthy. Modern dynamic languages seem to split on whether or not zero is falsy: Python, PHP, and Javascript say yes while Ruby, Lua, Clojure, and Racket say no.
Question is, why? I googled for my question title and found this thread on hacker news which had interesting stuff but not the answer to my question. Substituting 'lisp' for Clojure in my search yielded no historical reference.
So to be more precise in formulating my question: is there an actual technical advantage to zero evaluating as true in a conditional expression, or did it just become a quasi-standard in dynamic languages (that weren't as influenced by C) courtesy of the early lisps? Its definitely a bit odd to a programmer used to C/Python/Javascript.
The main reason is because many Clojure functions want to be able to easily tell "nothing" apart from "something". nil is the absence of a value, but the number 0 has a real value. An empty list is also a real thing, it's a sequence that could (for example) be conjed. (Though since Clojure allows you to (conj nil 1) that's perhaps not the best example.)
But the key distinction is that 0 is not "nothing", it's "something". Only "nothing" (and Boolean false) are going to be falsey in Clojure. It's a different way of thinking about falseness, and it can be jarring when you're coming from a Python background (as I did too), but I've actually found it more useful than Python's falsey mechanics.
One common idiom that pierce many languages is that language need something to represent nothing. C is one of the low-level of high-level languages that works with pointers directly, so it seems logical to make as nothing the impossible address, which is 0. So 0 pointer means nothing. And address can be considered (and actually it is) as a number. In Java there is null and in Clojure there is nil to represent nothing.
Question from the other side is: Should we consider something and nothing as bool values? In C, originally, there was no bool type, so they had to consider nothing as false (actually maybe in reverse: there is something and nothing so we don't need boolean type). In Clojure there is a boolean type and it differs from nil, but the simple rule of thumb works like this: "Nothing and false" coerce to FALSE and other to TRUE. So 0 is TRUE in Clojure. This was done, mostly to lisp original ideology, and, perhaps because time show that it is common case when you don't want to work with nothing, so you just check it.
Well, the answer is both yes and no, as far as I see it, the only advantage to having zero evaluated as a non-false value is to reserve that "special" trait to Null (or None).
In Python, for instance, not only 0 and None are false - but also an empty list ([]) and an empty string (''). This allows a very readable code (most of the time), but has the down-side of having to do some specific testing if you want to override any of this.
I can't figure out the difference between:
alts!
and
alt!
in Clojure's core.async.
alts! is a function that accepts a vector of channels to take from and/or channels with values to be put on them (in the form of doubleton vectors: [c v]). The vector may be dynamically constructed; the code calling alts! may not know how many channels it'll be choosing among (and indeed that number need not be constant across invocations).
alt! is a convenience macro which basically acts as a cross between cond and alts!. Here the number of "ports" (channels or channel+value pairs) must be known statically, but in practice this is quite often the case and the cond-like syntax is very clear.
alt! expands to a somewhat elaborate expression using alts!; apart from the syntactic convenience, it offers no extra functionality.
I'm looking for guidance on when to use Clojure BigInt versus Java BigInteger in Clojure. Both work just fine, and I am assuming that the main reason to use BigInt is to take advantage of operators like + and =, which have to be accessed via the Java instance methods .add and .equals, for instance. But there are few operators, such as isProbablePrime, that I can only access from BigInteger.
It seems pretty easy to shift from BigInt to BigInteger or vice versa, but the presence of both makes the use-cases unclear for me. My knee-jerk reaction is just to stick with BigInteger in the absence of clear criteria since some of the suggested usages seem not to work. From clojuredocs here:
user=> (def x (bigint 97))
user=> (.isProbablePrime x 1)
IllegalArgumentException No matching method found: isProbablePrime for class
clojure.lang.BigInt clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
In "Clojure Programming" by C. Emerick et. al., p.428, there is a sidebar topic, "Why Does Clojure Have Its Own BigInt Class When Java Already Provides One in BigInteger?"
They note two reasons to prefer BigInt to Java's BigInteger. First, the latter's .hashCode implementation is inconsistent with that of Long (the same number expressed in each type gives a different hash value). This is generally not what you want when comparing equivalent values in e.g. hash maps.
The other reason is that BigInts are optimized to use primitive types when possible, so performance should be better for many cases.
I would use Clojure's numeric types unless you have a good reason not to (your use of .isProbablePrime suggests you might have a good enough reason).
Three lispy homoiconic languages, Dylan, Julia and Seph all moved away from leading parenthesis - so a hypothetical function call in Common Lisp that would look like:
(print hello world)
Would look like the following hypothetical function call
print(hello world)
in the three languages mentioned above.
Were Clojure to go down this path - what would it have to sacrifice to get there?
Reasoning:
Apart from the amazing lazy functional data structures in Clojure, and the improved syntax for maps and seqs, the language support for concurrency, the JVM platform, the tooling and the awesome community - the distinctive thing about it being 'a LISP' is leading parenthesis giving homoiconicity which gives macros providing syntax abstraction.
But if you don't need leading parentheses - why have them? The only arguments I can think of for keeping them are
(1) reusing tool support in emacs
(2) prompting people to 'think in LISP' and not try and treat it as another procedural language)
(Credit to andrew cooke's answer, who provided the link to Wheeler's and Gloria's "Readable Lisp S-expressions Project")
The link above is a project intended to provide a readable syntax for all languages based on s-expressions, including Scheme and Clojure. The conclusion is that it can be done: there's a way to have readable Lisp without the parentheses.
Basically what David Wheeler's project does is add syntactic sugar to Lisp-like languages to provide more modern syntax, in a way that doesn't break Lisp's support for domain-specific languages. The enhancements are optional and backwards-compatible, so you can include as much or as little of it as you want and mix them with existing code.
This project defines three new expression types:
Curly-infix-expressions. (+ 1 2 3) becomes {1 + 2 + 3} at every place you want to use infix operators of any arity. (There is a special case that needs to be handled with care if the inline expression uses several operators, like {1 + 2 * 3} - although {1 + {2 * 3} } works as expected).
Neoteric-expressions. (f x y) becomes f(x y) (requires that no space is placed between the function name and its parameters)
Sweet-expressions. Opening and closing parens can be replaced with (optional) python-like semantic indentation. Sweet-expressions can be freely mixed with traditional parentheses s-expressions.
The result is Lisp-compliant but much more readable code. An example of how the new syntactic sugar enhances readability:
(define (gcd_ a b)
(let (r (% b a))
(if (= r 0) a (gcd_ r a))))
(define-macro (my-gcd)
(apply gcd_ (args) 2))
becomes:
define gcd_(a b)
let r {b % a}
if {r = 0} a gcd_(r a)
define-macro my-gcd()
apply gcd_ (args) 2
Note how the syntax is compatible with macros, which was a problem with previous projects that intended to improve Lisp syntax (as described by Wheeler and Gloria). Because it's just sugar, the final form of each new expression is a s-expression, transformed by the language reader before macros are processed - so macros don't need any special treatment. Thus the "readable Lisp" project preserves homoiconicity, the property that allows Lisp to represent code as data within the language, which is what allows it to be a powerful meta-programming environment.
Just moving the parentheses one atom in for function calls wouldn't be enough to satisfy anybody; people will be complaining about lack of infix operators, begin/end blocks etc. Plus you'd probably have to introduce commas / delimiters in all sorts of places.
Give them that and macros will be much harder just to write correctly (and it would probably be even harder to write macros that look and act nicely with all the new syntax you've introduced by then). And macros are not something that's a nice feature you can ignore or make a whole lot more annoying; the whole language (like any other Lisp) is built right on top of them. Most of the "user-visible" stuff that's in clojure.core, including let, def, defn etc are macros.
Writing macros would become much more difficult because the structure would no longer be simple you would need another way to encode where expressions start and stop using some syntactic symbol to mark the start and end of expressions to you can write code that generates expressions perhaps you could solve this problem by adding something like a ( to mark the start of the expression...
On a completely different angle, it is well worth watching this video on the difference between familiar and easy making lisps syntax more familiar wont make it any easier for people to learn and may make it misleading if it looks to much like something it is not.
even If you completely disagree, that video is well worth the hour.
you wouldn't need to sacrifice anything. there's a very carefully thought-out approach by david wheeler that's completely transparent and backwards compatible, with full support for macros etc.
You would have Mathematica. Mathematica accepts function calls as f[x, y, z], but when you investigate it further, you find that f[x, y, z] is actually syntactic sugar for a list in which the Head (element 0) is f and the Rest (elements 1 through N) is {x, y, z}. You can construct function calls from lists that look a lot like S-expressions and you can decompose unevaluated functions into lists (Hold prevents evaluation, much like quote in Lisp).
There may be semantic differences between Mathematica and Lisp/Scheme/Clojure, but Mathematica's syntax is a demonstration that you can move the left parenthesis over by one atom and still interpret it sensibly, build code with macros, etc.
Syntax is pretty easy to convert with a preprocessor (much easier than semantics). You could probably get the syntax you want through some clever subclassing of Clojure's LispReader. There's even a project that seeks to solve Clojure's off-putting parentheses by replacing them all with square brackets. (It boggles my mind that this is considered a big deal.)
I used to code C/C#/Java/Pascal so I emphasize with the feeling that Lisp code is a bit alien. However that feeling only lasts a few weeks - after a fairly short amount of time the Lisp style will feel very natural and you'll start berating other languages for their "irregular" syntax :-)
There is a very good reason for Lisp syntax. Leading parentheses make code logically simpler to parse and read, by collecting both a function and the expressions that make up it's arguments in a single form.
And when you manipulate code / use macros, it is these forms that matter: these are the building blocks of all your code. So it fundamentally makes sense to put the parentheses in a place that exactly delimits these forms, rather than arbitrarily leaving the first element outside the form.
The "code is data" philosophy is what makes reliable metaprogramming possible. Compare with Perl / Ruby, which have complex syntax, their approaches to metaprogramming are only reliable in very confined circumstances. Lisp metaprogramming is so perfectly reliable that the core of the language depends on it. The reason for this is the uniform syntax shared by code and data (the property of homoiconicity). S-expressions are the way this uniformity is realized.
That said, there are circumstances in Clojure where implied parenthesis is possible:
For example the following three expressions are equivalent:
(first (rest (rest [1 2 3 4 5 6 7 8 9])))
(-> [1 2 3 4 5 6 7 8 9] (rest) (rest) (first))
(-> [1 2 3 4 5 6 7 8 9] rest rest first)
Notice that in the third the -> macro is able in this context to infer parentheses and thereby leave them out. There are many special case scenarios like this. In general Clojure's design errs on the side of less parentheses. See for example the controversial decision of leaving out parenthesis in cond. Clojure is very principled and consistent about this choice.
Interestingly enough - there is an alternate Racket Syntax:
#foo{blah blah blah}
reads as
(foo "blah blah blah")
Were Clojure to go down this path - what would it have to sacrifice to get there?
The sacrifice would the feeling/mental-modal of writing code by creating List of List of List.. or more technically "writing the AST directly".
NOTE: There are other things as well that will be scarified as mentioned in other answers.
I've implemented a "big-int" in scheme as a list, so the first element is the sign of the number (+ or -) and the following are the value of the number itself, first the ones, then the tens etc.
For example: (+ 0 0 1) is for 100, (- 9 2 3 1) is for -1329 etc.
What I need now is to implement addition, subtraction and multiplication for big-ints implemented in this manner. I've done addition and subtraction, can someone help me with multiplication, please?
Break the problem up into smaller pieces. First, write a function that multiplies a Big-int by a single digit. Then, extend this (using Greg Hewgill's hint that you probably know how to do this on paper) to a function that multiplies a Big-int by a list of digits. Finally, wrap this in a function that accepts two Big-ints, strips off the sign, and then calls your previous function.
I strongly suggest that you write test cases for these functions before developing them.
here is a well known divide-and-conquer approach to big-int multiplication:
http://ozark.hendrix.edu/~burch/csbsju/cs/160/notes/31/1.html
This approach cuts the two numbers into halves and deals with them recursively. It is very fast, and it is easy to implement, despite the long explanation it may seem like. I highly recommend it. It takes all of about 10 lines of code in other languages, probably fewer in scheme :).