Why does the + function appear to work on tuples? - syntax

Using the + function on a tuple of two Int64s returns the sum:
julia> +((1, 2))
3
However, using the + function on a variable that references a tuple gives the following error:
julia> a = (1, 2)
(1,2)
julia> +(a)
ERROR: MethodError: no method matching +(::Tuple{Int64, Int64})
I'm having trouble understanding why it behaves like this, especially when the following code returns true.
julia> typeof(a) == typeof((1, 2))

Note that, contrary to what you might think,
julia> :(+((1, 2)))
:(1 + 2)
This is a single function call equivalent to (+)(1, 2). There is no tuple, although the syntax may look like there is a tuple. (The + function, as you noted, does not work on tuples.) Is this behavior desirable? Well it was reported as a bug #12755, but then fixed. But the fix caused bug #12771 which resulted in the fix being reverted by pull #12772.
The solution to this mess is to avoid calling operators as functions without explicitly writing parentheses. That is, always write (+)(1, 2) instead of +(1, 2). You can verify that (+)((1, 2)) throws the error that you expect.
(This problem only occurs with unary operators, hence why | and * are not subject to it.)
If you're interested, the heart of this problem is a fundamental ambiguity between +(x, y) function call syntax and unary operator syntax. Here are a few situations that motivate parsing + and - as unary operators, even when followed by (:
In -(x+y)^2, it is highly likely that (-)((x+y)^2) was meant, not ((-)(x+y))^2. So we cannot simply unconditionally parse -( as a function call.
Instead what must be done is the thing after - parsed up to a certain precedence, so that -x * y is parsed as (-x) * y, -x + y as (-x) + y, but -x^y as -(x^y).
Exception: But this would make -(1, 2) parse as (-)((1, 2)), that is, a function called on a tuple. For whatever reason or another, it was decided to add an exception for when the thing after - looks like a function call tuple. This is so that +(1, 2) would work, but this is really mostly just a hack.
But from the parser's perspective, ((1, 2)) looks exactly like (1, 2); just the former is wrapped in parentheses.
My personal opinion is that the -(1, 2) notation is silly (and doesn't work in all cases anyway; e.g. in -(1, 2)^2). If that exception weren't around, and -(1, 2) consistently parsed as a unary function call on a tuple, then more consistency could be had without (I think) much loss. It's not too bad to just write 1 - 2 or (-)(1, 2) when a binary function call is desired.

Related

How to acess argument from a function passed as argument in SML

I am new to coding SML and am still trying to understand pattern matching. I am trying to find out how to access an argument from a function passed as an argument in SML. For example, if a function takes 2 arguments, a function and an integer, how can I access the argument (for simplicity, assuming it only has one) that the argument function has. Does this question even make sense in SML? Here is some code, which doesn't work, but I think it illustrates what I am trying to do.
fun argumentExtraction (n,f) =
case f of
fn x => x
A function doesn't have arguments, it takes arguments. You give arguments to the function and you get a result back. You can't ask the function what its arguments are because it doesn't have them yet. You are supposed to give the arguments to the function.
To make this perhaps a bit clearer, let us consider an example. Let's take the following functions:
fun add x y = x + y
fun plus1 x = x + 1
fun applyTwice f x = f (f x)
Now applyTwice takes a function and an argument and applies the function to the argument twice. We can call it like this:
applyTwice plus1 40
or like this:
applyTwice (add 1) 40
and in both cases the answer is going to be 42 (because that's the value of plus1 (plus1 40) and of add 1 (add 1 40), add 1 really being the exact same function as plus1).
Now I'm not sure whether you want to be able to pass (plus1 40) as the value for f and then somehow get 40 from that or whether you want to pass (add 1) and then somehow get back the 1, but both are impossible.
In the case of (plus1 40) you can't even pass that as the value for f. f is supposed to be a function, but (plus1 40) is an integer (41), not a function.
(add 1) on the other hand is a function and you can indeed pass it as the value for f. In fact I did so in my example. But what you can't do is get the value 1 back from it. I mean, imagine there was a way that you could do that. What should then happen if you passed plus1 instead of (add 1). What should you get back from that? There is no value captured in plus1, so there's really nothing to get back, but clearly plus1 is just as valid an argument to applyTwice as (add 1).
The only way this could possibly make sense is if partially applied function had a different type from normal functions, allowing you to define a function that accepts (add 1) as one argument, but not plus1. However that's not the case ML and there's really not much benefit to that. Having different types of functions would just make the type system more complicated and make it more difficult to define higher order functions (as they'd have to be able to deal with both types of function). Nor do I see the use case where this ability would even be helpful.

Creating a counter Prolog

I'm trying to make a counter out of the following code:
contador([], 0,[]).
contador([via(A,_,_)|R], Tot,Regiao):-
cidade(A,_,_,Reg1),Reg1==Regiao,
Tr is Tot + 1,
contador(R,Tr,Regiao).
Given my list's format and cidade:
L=[via(porto,lisboa,_),via(braga,faro,_),via(guimaraes,santarem,_)]
cidade(lisboa,_,_,A)
Why isn't it working?
cidade(porto,portugal,40,litoral).
cidade(braga,portugal,350,interior).
cidade(guimares,portugal,40,litoral).
cidade(alverca,portugal,30,valedotejo).
cidade(santarem,portugal,25,valedotejo).
cidade(faro,portugal,20,litoral).
cidade(sevilha,espanha,60,interior).
With this list:
A = [via(porto, braga, 5), via(braga, guimaraes, 9), via(guimaraes, alverca, 7), via(alverca, faro, 10)] ;
I'm trying to do the following:
?-contador(A,Tot,litoral).
false.
My objective is to count the cities that have A(cidades(_,_,_,A)) as a parameter.
There are several issues in the code you presented.
1)
First, a remark, in Prolog, "=" is not an assignment like in C/C++ and other imperative languages. That means you can not type:
A=[...].
contador(...).
but use a single query:
A=[...],contador(...).
2)
These two statements are possibly an error:
contador([], 0,[]).
contador([via(A,_,_)|R], Tot,Regiao):-...
because third argument is in the first one a list, and is not in the second.
3)
Finally, what you call a "contador/counter" ( and that is, probably, better called an "accumulator" ) is not correctly "finished". When the original list is exhausted, the statement:
contador([], 0,[]).
is applied, but this statement request counter equal to cero. Probably, it will be better something like:
contador([], R, _) :- ... /* do something with R */
4)
These two statements:
cidade(A,_,_,Reg1),Reg1==Regiao,
can be unified in a single one:
cidade(A,_,_,Regiao),
5)
In general, try to skip "is" operator. By example, replace:
Tr is Tot + 1,
with:
succ(Tot,Tr),
6)
If statement:
cidade(A,_,_,Reg1),Reg1==Regiao,
fails, you have not an alternative rule.

Space before star breaks syntax in ruby multiplication statement

While adding some whitespace to make code more readable (line up with code above it), I came across this:
class C
def x
42
end
end
m=C.new
Now this will give "wrong number of arguments":
m.x *m.x
And this will give "syntax error, unexpected tSTAR, expecting $end":
2/m.x *m.x
What exactly is happening in the parser here?
I tested with Ruby 1.9.2 and 2.1.5.
* is used for both an operator (42 * 42) and argument unpacking (myfun *[42, 42]).
When you do:
m.x *m.x
2/m.x *m.x
Ruby interprets this as argument unpacking, rather than the * operator (ie. multiplication).
In case you're not familiar with it, argument unpacking (sometimes also called "splat", or "splats") means that you can have a function like this:
def myfun arg1, arg2; end
And call it like this:
myfun(*['Hello', 'World'])
arg1 is set to Hello, and arg2 is set to World.
I believe the rules are to determine which to use is:
Space before but not after a * -> Argument unpacking
Start of function parenthesis -> Argument unpacking
Everything else -> Multiplication (or rather, the * operator, since Ruby does operator overloading).
Good guidelines are:
Use the "optional" function parenthesis when you intend argument unpacking;
use spaces before and after * when you intend the * operator (multiplication).
Ruby will actually warn you about this when you run ruby -v:
test.rb|11 warning| `*' interpreted as argument prefix
test.rb|12 warning| `*' interpreted as argument prefix
In simple language:
When you say
m.x *m.x
It internally calls m.x(*m.x) i.e it considers *m.x as splat argument to m.x.
Since, there is an x method defined on m which takes any argument(s), you are getting the "wrong number of arguments" error.
When you call
m.x * m.x
It considers * as a method of x which takes an object of type 'Fixnum' and in Ruby, the * method that takes an argument is defined for 'Fixnum' class. So, it's the same as calling
m.x.*(m.x)
and hence it works!
I hope that helped you understand the problem, in case any clarification is required, feel free to comment.

How do I make a function use the altered version of a list in Mathematica?

I want to make a list with its elements representing the logic map given by
x_{n+1} = a*x_n(1-x_n)
I tried the following code (which adds stuff manually instead of a For loop):
x0 = Input["Enter x0"]
a = Input["a"]
M = {x0}
L[n_] := If[n < 1, x0, a*M[[n]]*(1 - M[[n]])]
Print[L[1]]
Append[M, L[1]]
Print[M]
Append[M, L[2]]
Print[M]
The output is as follows:
0.3
2
{0.3}
0.42
{0.3,0.42}
{0.3}
Part::partw: Part 2 of {0.3`} does not exist. >>
Part::partw: Part 2 of {0.3`} does not exist. >>
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]}
{0.3}
It seems that, when the function definition is being called in Append[M,L[2]], L[2] is calling M[[2]] in the older definition of M, which clearly does not exist.
How can I make L use the newer, bigger version of M?
After doing this I could use a For loop to generate the entire list up to a certain index.
P.S. I apologise for the poor formatting but I could find out how to make Latex code work here.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
It looks to me as if you are trying to compute the result of
FixedPointList[a*#*(1-#)&, x0]
Note:
Building lists element-by-element, whether you use a loop or some other construct, is almost always a bad idea in Mathematica. To use the system productively you need to learn some of the basic functional constructs, of which FixedPointList is one.
I'm not providing any explanation of the function I've used, nor of the interpretation of symbols such as # and &. This is all covered in the documentation which explains matters better than I can and with which you ought to become familiar.
Mathematica allows alphanumeric (only) names and they must start with a letter. Of course, Mathematic recognises many Unicode characters other than the 26 letters in the English alphabet as alphabetic. By convention (only) intrinsic names start with an upper-case letter and your own with a lower-case.
The underscore is most definitely not allowed in Mathematica names, it has a specific and widely-used interpretation as a short form of the Blank symbol.
Oh, LaTeX formatting doesn't work hereabouts, but Mathematica code is plenty readable enough.
It seems that, when the function definition is being called in
Append[M,L2], L2 is calling M[2] in the older definition of M,
which clearly does not exist.
How can I make L use the newer, bigger version of M?
M is never getting updated here. Append does not modify the parameters you pass to it; it returns the concatenated value of the arrays.
So, the following code:
A={1,2,3}
B=Append[A,5]
Will end up with B={1,2,3,5} and A={1,2,3}. A is not modfied.
To analyse your output,
0.3 // Output of x0 = Input["Enter x0"]. Note that the assignment operator returns the the assignment value.
2 // Output of a= Input["a"]
{0.3} // Output of M = {x0}
0.42 // Output of Print[L[1]]
{0.3,0.42} // Output of Append[M, L[1]]. This is the *return value*, not the new value of M
{0.3} // Output of Print[M]
Part::partw: Part 2 of {0.3`} does not exist. >> // M has only one element, so M[[2]] doesn't make sense
Part::partw: Part 2 of {0.3`} does not exist. >> // ditto
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]} (* Output of Append[M, L[2]]. Again, *not* the new value of M *)
{0.3} // Output of Print[M]
The simple fix here is to use M=Append[M, L[1]].
To do it in a single for loop:
xn=x0;
For[i = 0, i < n, i++,
M = Append[M, xn];
xn = A*xn (1 - xn)
];
A faster method would be to use NestList[a*#*(1-#)&, x0,n] as a variation of the method mentioned by Mark above.
Here, the expression a*#*(1-#)& is basically an anonymous function (# is its parameter, the & is a shorthand for enclosing it in Function[]). The NestList method takes a function as one argument and recursively applies it starting with x0, for n iterations.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
No underscores, they're used for pattern matching. Otherwise a variable can contain alphabets and special characters (like theta and all), but no characters that have a meaning in mathematica (parentheses/braces/brackets, the at symbol, the hash symbol, an ampersand, a period, arithmetic symbols, underscores, etc). They may contain a dollar sign but preferably not start with one (these are usually reserved for system variables and all, though you can define a variable starting with a dollar sign without breaking anything).

Lisp Parentheses

Why do Lispers format their code like shown in sample 1 instead of as shown in sample 2? To me (and I guess, to most others coming from different programming backgrounds than Lisp), the formatting shown in sample 2 would be easier to read. Is there any particular reason why Lispers prefer the sample 1 style?
Sample 1
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
Sample 2
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))
)
)
LISP IDE environments tend to balance parentheses automatically and manage indents based on nesting level. Sample 2 does not bring any advantages in those situations.
In the C/FORTRAN/Pascal heritage, you tend to emphasize sequencing over nesting (code parse trees are shallower and wider). End of scope is a more significant event in your code: hence emphasis has been and still to some extent is more important.
For experienced Lisp users, the nesting level is more important than finding closing parentheses. Putting closing parentheses on their own lines does not really help with nesting levels.
The basic idea is that the parentheses are directly AROUND their contents.
(a)
and not
(a
)
What follows is this:
(defun foo (bar)
(foo (bar (baz
...
)
...
)
...
)
)
vs.
(defun foo (bar)
(foo (bar (baz ...) ...) ...))
One of the basic ideas when editing Lisp text is, that you can select a list by (double-) clicking on the parentheses (or by using a key command when the cursor is inside the expression or on the parentheses). Then you can cut/copy the expression and paste it into another position in some other function. Next step is to select the other function and
re-indent the function. Done. There is no need to remove or introduce new lines for for closing parentheses. Just paste and re-indent. It just fits in. Otherwise you would either waste time formatting the code, or you would need to re-format the code with some editor tool (so that closing parentheses are on their own lines. Most of the time it that would create additional work and hinders moving code around.
There is one occasion where experienced Lispers would sometime write closing parentheses on their own line:
(defvar *persons*
(list (make-person "fred")
(make-person "jane")
(make-person "susan")
))
Here it indicates that new persons can be added. Place the cursor directly before the second closing parentheses on the last line, press c-o (open line), add the clause and indent the parentheses that they are aligned again. This saves the 'trouble' to find the right parentheses and then press return, when all parentheses are closed on one line.
Because there is no need whatsoever to line up closing parens. It doesn't add anything semantically. To know how many to close, most Lispers use a good editor, such as Emacs, that matches parens to closing parens and hence makes the task trivial.
In Python, there are no closing parens or end keywords at all, and Pythonistas live just fine.
After a while with Lisp you don't notice the parentheses any longer, so your example two comes across as having a bunch of unnecessary whitespace in the end of it. More specifically, most lispers use an editor that is aware of parentheses and takes care of closing the forms correctly, so you as the developer don't need to match opening and closing parentheses like you do in e.g. C.
As for whether the last form should be
(* n (factorial (- n 1)))
or
(* n
(factorial (- n 1)))
that mostly comes down to personal preference and how much stuff is going on in the code (In this case I'd prefer the former just because there is so little happening in the code).
Besides the fact that most Lisp IDE's use paren matching, the amount of space that you would use to write any reasonable program would be ridiculous! You would get carpal tunnel from all the scrolling. A 1,000 line program would be close to a million lines of code if you put all the closing parenthesis on their own line. It may look prettier and be easier to read in a small program, but that idea wouldn't scale well at all.
Why do C programmers write things like:
((a && b) || (c && d))
instead of
((a && b) || (c && d
)
)
Wouldn't #2 be easier to read? :)
Seriously, though, the bunched up closing style works well for other languages, too.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{ int i, j, k;
for (i = 0; i < 1000; i++)
{ for (j = 0; j < 1000; j++)
{ for (k = 0; k < 1000; k++)
{ if (i * i + j * j == k * k)
{ printf("%d, %d, %d\n", i, j, k); } } } }
return 0; }
After a while, you don't "see" the braces, just the structure given by the indentation.
if/else looks like this:
if (cond)
{ stmt;
stmt; }
else
{ stmt; }
switch:
switch (expr)
{ case '3':
stmt;
break;
case '4':
{ stmt;
break; } }
structs:
struct foo
{ int x;
struct bar
{ int y; };
union u
{ int a, b;
char c; }; };
Just first and obvious reason: 4 LOC in first case vs. 7 LOC in second one.
Any text editor that is aware of LISP syntax will highlight you matched/mismatched parentheses, so it's not the problem.
I experienced the same dilemma in PHP using the CakePHP framework and its many nested array() structures, sometimes 5+ layers deep. After a short while I realized that being OCD about the closing parenthesis did nothing but waste my precious development time and distracted me from the end goal. The indentation was to be the most useful aspect of the formatting.
Saving all the space seems like the primary reason. If it's almost as readable (esp. once you're used to the syntax) why use the extra 3 lines.
Because Lisp programmers look at the indentation and "shape", not the brackets.
You might consider Lisp variants which do without the (). In Genyris it looks like this:
def factorial (n)
if (< n 2) 1
* n
factorial (- n 1)
Seems like this is not a real question, just a judgement on Lisp, but the answer is perfectly obvious (but not, apparently, to non-Lispers!): parentheses in Lisp are in no way equivalent to braces in C-like languages -- rather, they're precisely equivalent to parentheses in C-like languages. Lispers don't generally write
(foo bar baz
)
for exactly the same reason C programmers don't generally write
foo(bar, baz
);
The reason
(if foo
(bar)
(baz))
looks different from
if (foo) {
bar();
} else {
baz();
}
has more to do with the if than the parentheses!
I have an explanation as to C programmers have a problem with Lispers putting all the remaining closing parentheses at the end. The practice seems to me that the meaning of parentheses could be the reason. This explanation overlaps and expands on some other answers.
To a C programmer (or other language using {braces} like C does), Lisp looks like it uses #| comments |# instead of /* comments */. And looks like Lisp parentheses () are in place of C braces {}.
But really, the Lisp parentheses mean very close to the same thing as in C (and similar languages using parentheses). Consider
defun f () nil
This defines a function f that does absolutely nothing, nil. And I type that line exactly as is into the Lisp Listener, and it just responds "F". In other words, it accepts it, without a beginning and ending parentheses around the whole thing.
What I think happens when you type that into the Listener is the Listener passes what you typed to Eval. Passing it to Eval could be represented as:
Eval( Listener() )
And Listener accepts my input and returns what I typed. And you would consider "Listener()" replaced in the expression so that it becomes
Eval (defun f () nil)
REPL (read, eval, print, loop) could be represented conceptually as a recursion
/* REPL expressed in C */
Loop()
{
Print ( Eval ( Listen () ) );
Loop();
}
Understood in the example is that Listen(), Eval(), and Print() are defined elsewhere or are built into the language.
The Listener lets me type
setf a 5
and also lets me type
(setf a 5)
but complains when I type
((setf a 5))
If parentheses were equivalent to C language braces, then the listener would accept it. In my C\C++ compilers, I can type
void a_fun(void)
{{
}}
without complaint. I can even type
void a_fun(void)
{{{
}}}
with no complaint from the C/C++ compiler.
But if I dare to type
void a_fun((void))
{
}
my C/C++ compiler complains--just like the Lisp listener complains!
For a C programmer writing nested function calls, seems it is more natural to write
fun_d( fun_c( fun_b( fun_a())));
than to write
fun_d( fun_c( fun_b( fun_a()
)
)
);
In C, braces demarcate a block of code. And a block of code is part of a function definition. Lisp parentheses don't demarcate blocks. They are somewhat like C's parentheses. In C, the parentheses demarcate a list; maybe a list of parameters passed to a function.
In Lisp, seems the opening parentheses "(" means we are going to start a new list, to which the CAR side of a CONS construct will point. Then we list the items to be contained or optionally pointed to by the CAR side of the CONS, with the CDR side pointing to nil (for end of list) or the next CONS. The closing parenthesis ")" means to terminate the list with a nil, and go back to continue the previous level of listing. So, C language does not do CONS's. So, there is a little bit of a difference between C's parentheses and Lisp's. Even so, seems very close, maybe even practically the same thing.
Some have written that Lisp becomes more like C if you move the function outside the parentheses. For example,
(setf a 5)
becomes
setf(a 5)
But what it really is, is that Eval requires that the first item in a list be the function that Eval needs to call. It is more like passing a C function a pointer to a function. So, what it really is is
eval(setf a 5)
And that looks more like C. You can even type it in the listener just like that without complaint from the listener or eval. You are just saying that eval should call eval which should then call setf. The rest of the list are parameters to setf.
Anyway, that's just what I think I see.
It's just that Eval needs to know which processor to call.
And I think this explanation provides an understanding of why C programmers think initially that Lispers should align closing parentheses under the opening parentheses which they close. The C programmer mistakenly thinks that Lisp's parenthesis correspond to C's braces. They don't. Lisp's parentheses correspond to C's parentheses.

Resources