Why doesn't elm use parenthesis? - elm

Learning elm but don't get what author means by the below:
The reason we can avoid writing the parenthesis is because function
application associates to the left.

Any values or functions, specified after the function name, will be associated with the function as it's arguments automatically, that's really all it means.
In language, like JavaScript, you can explicitly distinguish the usage of a function, as an expression:
function foo (message) {
return message
}
console.log(foo) // Function as expression.
console.log(foo('Hello')) // Function application with result: "Hello"
In Elm this behaviour does not require parentesis.
foo message =
message
foo -- Function as expression.
foo "Hello" -- Function application with result: "Hello"
It's not like in JavaScript at all, when you want to apply the function and do something with result. Here you will have to tell the compiler explicitly, that (foo "Hello") is a single argument for String.toUpper
String.toUpper (foo "Hello") -- "HELLO"

The parentheses in question is ((divide 5) 2). My interpretation of that sentence is that you can write ((divide 5) 2) as divide 5 2 because divide 5 2 is evaluated from the left first, i.e. divide 5 -> divide5 then divide5 2 -> 2.5.
Though I can't see how else it could be evaluated! Neither 5 2 nor divide 2 then divide2 5 make sense.

Related

Use of mathematical operator at start of line

I have a basic question for my general knowledge of Kotlin concerning the mathematical operators:
I was writing an equation and I mistakenly put the plus sign on the second line which caused my equation not to work as on the examples below:
val x = 2 + 3 //x = 5 CORRECT
val x = 2 +
3 //x = 5 CORRECT
val x = 2
+ 3 //x = 2 WRONG
My question is: why Kotlin is not showing any error message on the last example? How is Kotlin interpreting the line "+3"?
val x = 2 is correct expression, so compiler uses it as complete expression.
+ 3 is correct expression although it doing nothing.
val x = 2 + is uncompleted expression - the compiler is trying to complete it using the next line.
This is an unfortunate result of the way Kotlin assumes a semicolon at the end of lines.
In languages like Java, every statement must end with a semicolon, so there's no ambiguity.
Kotlin allows you to omit semicolons, which can be handy.  But it's a bit over-eager: it infers one at the end of every line that would make sense on its own, ignoring the following lines.  This is rather annoying to those of us who like to put operators at the start of a line, not the end…
Most of the time, the following line won't make sense on its own, so you get a compiler error to warn you of the issue.  Unfortunately, you've found one of the rare cases where the following line is valid, and so there's no error!  (Kotlin has a unary plus to match its unary minus, so +3 is a number just like -4.  And a number on its own is a valid expression.  Kotlin calculates the value, and then discards it.)
The solutions are:
Put the whole expression on the one line.  (Which is unwieldy if it's long!)
Put the operator at the end of the previous line.  (Which is clearly what the language designers expect, but some of us find less logical and less clear.)
Prevent the first line from making sense on its own.
The best way I've found to do that last one is with parens:
val x = (2
+ 3)
It looks awkward in a very short expression, but it works reasonably well on longer ones — not ideal, but necessary unless/until Kotlin gets smarter about where to assume semicolons…

List repetition (xx) without evaluation?

The list repetition operator (xx) evaluates the list every time it is repeated. For example,
my #input = get() xx 5;
will evaluate to the first 5 lines of STDIN. Is there any way I can repeat just the value of the element 5 times, rather than evaluating it each time? Currently, I've been assigning it to a variable, then repeating it, but it seems a bit cumbersome that way.
my $firstLine = get();
my #firstlineRepeated = $firstLine xx 5;
Is there a prefix or something that lets me do it in one statement?
Using given to contextualize it into $_ is one fairly neat way:
my #input = ($_ xx 5 given get());
say #input;
That, when I type hello, gives:
[hello hello hello hello hello]
Since given simply contextualizes, rather than doing any kind of definedness or truth test, it's a bit safer as a general pattern than andthen.
You could try use the andthen operator:
my #input = (get() andthen $_ xx 5);
From the documentation:
The andthen operator returns Empty upon encountering the first
undefined argument, otherwise the last argument. Last argument is
returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to $_ for the
right side, or passed as arguments if the right side is a Callable,
whose count must be 0 or 1.
Using phrase ENTER works too
my #input = ENTER { get() } xx 5;

When does = perform comparison instead of assignment?

In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable:
Private Function foo() As Boolean
Dim bar As Integer = 1
Return bar = 2
End Function
Returns: False
OK, but what's the value of bar?
Private Function foo() As KeyValuePair(Of Boolean, Integer)
Dim bar As Integer = 1
Return New KeyValuePair(Of Boolean, Integer)(bar = 2, bar)
End Function
Returns: False, 1
It looks like = will perform a comparison when the statement context demands it, but is this guaranteed? That is, can I be sure that bar will never be set to 2 in this situation?
Also, I know that VB.NET doesn't allow chained inline assignments, which may be for the best. Does this odd = behavior cause any other quirks I should be aware of?
You cannot do in-line assignments in VB, Assignment is an explicit statement:
[Let] <<target-reference>> = <<value-expression>>
The Let is optional and implicit, and hardly ever used anymore. The general rule that you can use to distinguish the [Let] command from equality testing is that for Let, no other keyword may come before the target-reference in the statement. AFAIK, in all cases of = as equality testing, there is one or more other keywords that precede it in the statement.
In your first example, the keyword Return precedes your =, so it's an equality test, and not an assignment.
In your first example you can do either:
Return 2
or
bar = 2
Return bar
As for your question "OK, but what's the value of bar?", bar still equals one.
= in VB cause no quirks. It works exactly as documented, and it always has (including its predecessor, BASIC back to 1968).
If you are starting to code in VB (coming from a language like C#), you should start getting used to the peculiar VB way of doing things; which is based on the idea: as simple and intuitive for the programmer as possible. "If assignation and comparison happen always in different contexts, why not using the same operator and let the context define its exact meaning?" -> VB-way of seeing things. "No, different realities have to be accounted for by different operators. End of the discussion" -> C#-way. :)
Is this reliable? Can you blindly trust on these not-always-clear-for-a-programmer bits? Sure, VB.NET peculiarities are highly-reliable and trustworthy. You can always use = (or Is on some contexts, but VS would tell you) and be completely sure that the code will do what is expected. But the question is: are you sure that you write exactly what you want?
This last question is what, perhaps, is more criticable of VB and what might give some problems to programmers from other languages: the higher the flexibility, the more likely is that you make an error; mainly if you are used to a different format.
Regarding the chained inline assignments, I honestly don't see its true utility (and never use them in C#). Regarding other differences with respect to C#, there are plenty of them; in some cases, I think that the C# approach is better; other times, the VB.NET one. On readability/length of code, I can refer to the With Statement I have always found somehow useful which is not present in C#.
One way to have 100% sure that the expression will be evaluated as an boolean expression is to use ()
e.g
Dim a = 2
Return (a = 1)
Since you cannot set a value to a variable wihtin the parenthesis.
What i want to say is: on an return statament for example you cant assing a value to a variable so, even if you use
a = 1
The compilator knows that this expression only can be an boolean expression.
The same to the if statament and so on..
Heh back in QB45 days we used to exploit the fact that "True" was the numeric value -1. So you would see code like x = 1 - x * (x < 6) (translation: increment x, but reset to 1 when it gets to 6)

Lua function call with parameter list in a string

Is it possible in LUA to execute a function like foo("param1, param2, param3, param4"), and have it detect it as foo(param2, param2, param3, param4)
Why?
I have a scenario where a function can receive as many parameters as I wish, and they can't be sent as a list (It's in CoronaSDK, so I can't really modify the source, and have to adapt to it). So, sometimes I'll have to send 3 parameters, while sometimes I'll be sending 100. Is there anyway of doing this?
they can't be sent as a list (It's in CoronaSDK, so I can't really modify the source, and have to adapt to it)
Sure it can. Watch:
function CallWithParametersInAList(FunctionToCall, paramsInList)
return FunctionToCall(unpack(paramsInList))
end
See? Every array element in paramsInList will be unpacked into arguments to FunctionToCall. Also, every return value from FunctionToCall will be returned.
see
function test(a)
print("this is lua test function."..a);
end
CallWithParametersInAList(test,{33333});
OUTPUT
this is lua test function.33333
You can call a lua function with as many parameters as you want. If the function expects more parameters, they will be set to nil. If the function expects too few parameters, the extra parameters sent will get ignored.
For example:
function f(a, b, c)
print(a, b, c)
end
f(1, 2) -- prints: 1 2 nil
f(1, 2, 3) -- prints: 1 2 3
f(1, 2, 3, 4, 5) -- prints: 1 2 3
edit:
If you must get the parameters from a string and those parameters include things like tables and functions, you have little option but to get the string parsed by loadstring function:
-- s contains the parameters
s = '1,2,{1,2,3}'
-- f is the function you want to call
loadstring('f(' .. s .. ')')() -- prints: 1 2 table: 0061D2E8
I'm not sure about CoronaSDK, but the loadstring function tends to be a bit slow. Try to avoid it if possible.
One of the best methods, in my opinion(and the one I use) is something like this:
function Call( ... )
-- All passed arguments are stored in a default table named arg
table.foreach( arg, print )
end
And, here's a working example on codepad - oDmVZ209.
I'd second Nicol Bolas that you are probably trying to solve the wrong problem, but if you still want to parse the string and turn it into a list of parameters, here is one way to do this (loadstring is not available in Corona environment; obviously this doesn't handle any type of hierarchical data):
function str2list(s)
local parms = {}
for p in s:gmatch("([^,]+),?") do table.insert(parms, p) end
return unpack(parms)
end
print(str2list("param1, param2, param3, param4"))

Rebol simulating unlimited args any example from what is said here?

http://www.rebol.org/ml-display-thread.r?m=rmlJNWS
Graham wrote:
Can a function have a variable number of arguments?
No. But you can simulate it, by using 'any-type! function specifiers and passing unset! as arguments. Better is to use refinements.
Rebol's default dialect (the do dialect) does not support the notion of a call to a function having a variable number of arguments. If you want to break a rule as fundamental as this, then you need your own dialect. Nothing stopping you from making:
tweet [Hello World How Are You Today?]
But the idea of using word! instead of string! in this case is a little dodgy, as many common tweets aren't valid for the Rebol parser:
tweet [LOL! :)]
Neglecting that issue, note that by default you won't get any expression evaluation. So this tweet dialect would have to choose a way to show where you want an evaluation. You might use get-word elements to do variable substitution, and parentheses for more general evaluations:
>> a: 10
>> b: 20
>> tweet [When you add :a and :b you get (a + b), LOL ":)"]
"When you add 10 and 20 you get 30, LOL :)"
BTW, take-n in Rowland's example isn't returning a block. Not directly, I mean. It's perhaps better understood with parentheses, and by addressing the implicit "do" that's there on every interpretation:
do [do (take-n 4) 1 2 3 4]
take-n works with only one parameter (the "n") and then returns a function which takes n parameters. Let's call that function f, so step one of this evaluation turns into something equivalent to:
do [f 1 2 3 4]
When the second do kicks in, that function gets run...and it's returning a block. In practice, I doubt you're going to want to be counting the parameters like this.
The answer on that page is:
yes, a function can have a variable number of arguments. Do is such a function, as e.g. in:
take-n: func [n /local spec] [
spec: copy []
for i 1 n 1 [
append spec to word! append copy "a" to string! i
]
func spec reduce [:reduce append reduce [to lit-word! append copy "take" to string! n] spec]
]
do take-n 4 1 2 3 4
== [take4 1 2 3 4]