News for hackers. Stuff that matters.
Re:Why Does “=” Mean Assignment? by rdtsc on Tuesday April 10, 2018 @03:54PM (#16804667)
Another interesting way to think about it is as "match". That is try to match the stuff on the right with the stuff on the left.

Take Erlang for example:

    1> X = 1.
    1
    2> X = 2.
    ** exception error: no match of right hand side value 2
Notice variables are immutable (not just values themselves). Once X becomes 1, it can only match with 1 after that. You might think this is silly or annoying, why not just allow reassignment and instead have to sprinkle X1, X2 everywhere. But it turns out is can be nice because it makes state updates very explicit. In complicated applications that helps understand what is happening. And it behaves like you'd expect in math, in the sense that X = X + 1 doesn't make sense here either:

    1> X = 1.
    1
    2> X = X + 1.
    ** exception error: no match of right hand side value 2
    3>    
It does pattern matching very well too, that is, it matches based on the shape of data:

    1> {X,Y} = {1,2}.
    {1,2}
    2> X.
    1
    3> Y.
    2
    4>
In other languages we might say we have assignment and destructuring but here it is rather simple it's just pattern matching.
Re:Why Does “=” Mean Assignment? by macintux on Tuesday April 10, 2018 @04:13PM (#16804858)
I'm sure I've mentioned it here before, but in my favorite Erlang talk I design the language with the equal sign as my core construct.

Since the equal sign is an assertion of truth, and since assertions cause a crash on failure, you can pretty much derive the rest of the language/BEAM characteristics from that.

Re:Why Does “=” Mean Assignment? by rdtsc on Tuesday April 10, 2018 @05:44PM (#16805785)
Thanks for sharing. Enjoyed watching (from the link below). Well done!

I like the '=' as an assertion idea. That is, it's like running code with assertions turned on. Never thought about it that way but it makes good sense.

Also stealing your idea of "rebootable code" :-)

Re:Why Does “=” Mean Assignment? by macintux on Wednesday April 11, 2018 @09:17AM (#16810772)
I'm sure I stole the idea of rebootable code from someone else, but I'll be happy to take credit for it.

I almost submitted the talk to That Conference this year. I should start shopping it around more.

Re:Why Does “=” Mean Assignment? by hwayne on Tuesday April 10, 2018 @04:34PM (#16805057)
I don't think I've heard of this before; I'd love to watch it if you have a link!
Re:Why Does “=” Mean Assignment? by Artemix on Tuesday April 10, 2018 @04:35PM (#16805073)
I'd also want to see the link, if available!
Re:Why Does “=” Mean Assignment? by macintux on Tuesday April 10, 2018 @04:44PM (#16805163)
This is from a few years ago, my first time giving it, and I've never had the courage to actually watch it, so ymmv.

https://youtu.be/E18shi1qIHU

Re:Why Does “=” Mean Assignment? by Sholmesy on Wednesday April 11, 2018 @04:30AM (#16809120)
Dude, this was great. Been looking to get into Erlang, but the "unfamiliarity" always shunned me away. Really nice talk.
Re:Why Does “=” Mean Assignment? by macintux on Wednesday April 11, 2018 @09:15AM (#16810761)
Thanks, glad you liked it. I love teaching Erlang.
Re:Why Does “=” Mean Assignment? by derefr on Tuesday April 10, 2018 @05:25PM (#16805607)
Also valid in Erlang:

    2 = X.

    {ok, Y} = X = foo().
Oh, and here's a fun one:

    1> {X, X} = {1, 1}.
    {1, 1}.
    2> {Y, Y} = {1, 2}.
    ** exception error: no match of right hand side value {1,2}
If you're wondering what the use of that is, here's an Erlang "drop all occurrences of an element X from a list" function. (Prerequisite knowledge for this: Erlang functions have several clause-heads; which one is executed on each call depends on which one is able to successfully bind to—i.e. = with—the arguments.)

    drop(X, List) -> drop(X, List, []).

    drop(X, [], Acc) -> lists:reverse(Acc);
    drop(X, [X|Rest], Acc) -> drop(X, Rest, Acc);
    drop(X, [Y|Rest], Acc) -> drop(X, Rest, [Y|Acc]).
In other words—first, set up an accumulator. Then, go through the list, and if X can bind in both positions, skip the element; otherwise (i.e. if Y != X) then shift Y into the accumulator. At the end, reverse the accumulator (because you were shifting.)
Re:Why Does “=” Mean Assignment? by triska on Tuesday April 10, 2018 @05:38PM (#16805723)
To illustrate how close Erlang syntax is to Prolog, here is drop/3 in Prolog:

    drop(X, List, Result) :- drop(X, List, [], Result).

    drop(_, [], Acc, Result) :- reverse(Acc, Result).
    drop(X, [X|Rest], Acc, Result) :- drop(X, Rest, Acc, Result).
    drop(X, [Y|Rest], Acc, Result) :- dif(X, Y), drop(X, Rest, [Y|Acc], Result).
I only had to make a few syntactic changes to the original program to obtain a Prolog predicate from it. The most significant change is that I use an additional argument to hold the original function's return value. An important consequence of the resulting relational nature is that this can answer quite general queries.

For example, we can ask: What are possible solutions Ls that arise when we drop X from the single-element list [A] ?

    ?- drop(X, [A], Ls).
    X = A,     Ls = [] ;
    dif(X, A), Ls = [A].
We see that there are two possible answers: One where X is A, and hence the result is the empty list []. And the other where X is different from A, as indicated by dif(X, A).

Even more generally, we can systematically enumerate all conceivable solutions for all list lengths:

    ?- length(Ls0, _), drop(X, Ls0, Ls).
    Ls0 = Ls, Ls = [] ;
    Ls0 = [X],
    Ls = [] ;
    Ls0 = Ls, Ls = [_586],
    dif(X, _586) ;
    Ls0 = [X, X],
    Ls = [] ;
    Ls0 = [X, _598],
    Ls = [_598],
    dif(X, _598) ;
    etc.
This uses iterative deepening to generate all possible answers.
Re:Why Does “=” Mean Assignment? by kqr on Wednesday April 11, 2018 @12:48AM (#16808115)
Also not stuck using only an unbound result. Could we not ask "given L and Ls, what elements were dropped?"
Re:Why Does “=” Mean Assignment? by triska on Wednesday April 11, 2018 @01:54AM (#16808401)
Yes, that's also possible with this definition! For example: Given Ls0 = [a,b,c] and Ls = [a,c], which element (if any) was dropped:

    ?- drop(X, [a,b,c], [a,c]).
    X = b ;
    false.
As another example, if both Ls0 and Ls are [a,b,c]:

    ?- drop(X, [a,b,c], [a,b,c]).
    dif(X, c),
    dif(X, b),
    dif(X, a).
This means that X must be different from each of these elements.

More generally, which elements can be dropped at all from the list [a,b,c]:

    ?- drop(X, [a,b,c], _).
    X = a ;
    X = b ;
    X = c ;
    dif(X, c),
    dif(X, b),
    dif(X, a).
Interestingly, the predicate definition does not even use "=" in its clauses. In Prolog, (=)/2 is a built-in predicate that means unification. In the definition above, we use implicit unification instead of explicit unification.
Re:Why Does “=” Mean Assignment? by Tarean on Wednesday April 11, 2018 @01:23AM (#16808287)
I have mixed feelings on this. On one hand I did want this notation while learning haskell. Partly because there are a bunch of places in haskell's type system where repeating a variable implicitly gives equality constraints.

On the other hand something like

    drop _ [] = []
    drop x (y:xs)
        | x == y = drop x xs
        | otherwise = y : drop x xs
is often more readable at a glance to me since I don't have to parse variable names to see control flow structures.

Also, in statically typed languages what happens if equality doesn't work for a value.

Re:Why Does “=” Mean Assignment? by icebraining on Tuesday April 10, 2018 @04:08PM (#16804815)
Prolog's unification:

  X = Y,
  X = 5,
  %% Y = 5 now as well
--

  ?- append([1,2], Y, [1,2,3]).
  Y = [3].
Re:Why Does “=” Mean Assignment? by OskarS on Tuesday April 10, 2018 @05:05PM (#16805418)
Yeah, Prolog's unification operator really blows your mind the first few times you experience it. You left the best part out of that last example:

    ?- append(X, Y, [1,2,3]).
    X = [],
    Y = [1, 2, 3] ;

    X = [1],
    Y = [2, 3] ;

    X = [1, 2],
    Y = [3] ;

    X = [1, 2, 3],
    Y = [] ;

    false.
(a few newlines added for clarity)
Re:Why Does “=” Mean Assignment? by rcharles on Tuesday April 10, 2018 @04:25PM (#16804972)
Some(all?) compilers transform your code into something like this internally. Its called static single assignment form. https://en.wikipedia.org/wiki/Static_single_assignment_form
Re:Why Does “=” Mean Assignment? by njitbew on Tuesday April 10, 2018 @05:08PM (#16805445)
Though it's true that compilers usually turn assignments into SSA, that's not really the same as what parent was referring to. Static single assignment has the same semantics as normal C-style assignments. The parent was referring to assignments that have (Erlang's) pattern match semantics.

Also, there's a simple counterexample. You can have static single assignment that has dynamic multiple assignment (e.g. within a loop construct). Under the pattern-matching semantics, evaluating the assignment (or rather the pattern match) a second time could fail, whereas an assignment always succeeds.

Re:Why Does “=” Mean Assignment? by bogomipz on Wednesday April 11, 2018 @07:04AM (#16809836)
>"Though it's true that compilers usually turn assignments into SSA"

What is SSA here?

Re:Why Does “=” Mean Assignment? by macintux on Wednesday April 11, 2018 @08:46AM (#16810528)
Static single assignment (see Wikipedia link in grandparent).
Re:Why Does “=” Mean Assignment? by aprao on Tuesday April 10, 2018 @05:16PM (#16805520)
Elixir has borrowed the pattern matching approach from Erlang, but allows rebinds which makes code refactoring easier.

iex(1)> x = 1 1 iex(2)> x = 2 2 iex(3)> ^x = 3 (MatchError) no match of right hand side value: 3

Notice the pin operator (^) to achieve the same effect.

Re:Why Does “=” Mean Assignment? by dxhdr on Tuesday April 10, 2018 @05:27PM (#16805624)
I've used Erlang but not Elixir. Having an additional optional "pin" operator sounds like a bad idea, just piling on complexity. You can't mess up with the Erlang syntax.
Re:Why Does “=” Mean Assignment? by glorioustao on Tuesday April 10, 2018 @07:21PM (#16806581)
The creator of elixir had a blog on this: http://blog.plataformatec.com.br/2016/01/comparing-elixir-an...
Re:Why Does “=” Mean Assignment? by gcb0 on Wednesday April 11, 2018 @05:16AM (#16809333)
only the case argument there is any good. when it get to numbered vars, you know they are grasping for anything
Re:Why Does “=” Mean Assignment? by ninjakeyboard on Wednesday April 11, 2018 @08:37AM (#16810451)
Ya +1 I've been working with elixir lately and the `=` operator in erlang/elixir is the first thing that came to mind when I saw this.
Re:Why Does “=” Mean Assignment? by bogomipz on Wednesday April 11, 2018 @07:02AM (#16809831)
>"In other languages we might say we have assignment and destructuring ..."

I'm not familiar with this term "destructuring." Can you elaborate on the concept? Might you have an example of a destructure operation and a language where its's used?

Re:Why Does “=” Mean Assignment? by ajuc on Wednesday April 11, 2018 @07:25AM (#16810011)
https://clojure.org/guides/destructuring

Basically it means that you can assign several variables at once, by asssigning a complex value to an aproprietly structured literal with variables as placeholders.

In pseudojavascript, let's say you got this from some API:

    var someList = [1, 2, 3, 4];
    var someMap = { name: "John Smith",
                    age: 20,
                    cars: [{ id: "AAA-1111", model: "Ford T"},
                           { id: "AAA-1112", model: "Mercedes Benz"}] }
And you want to extract useful data for your code quickly. In languages with destructuring you can do sth like this:

    var [x, y & rest] = someList; //x==1, y==2, rest == [3, 4]
    var { "name": name,
          "age": age,
          "cars": [ {"id": firstCarId, "model": firstCarModel}
                  & restOfTheCars ]
        } = someMap;
And the language will put the correct values in your variables name, age, firstCarId, firstCarModl, restOfTheCars.
Re:Why Does “=” Mean Assignment? by OvermindDL1 on Wednesday April 11, 2018 @10:28AM (#16811394)
Javascript itself supports destructuing fine, here's some javascript straight from the firefox console:

    > let a = [1,2,3]
    undefined
    > [x,y,z] = a
    Array(3) [ 1, 2, 3 ]
    > x
    1
    > y
    2
    > z
    3
Re:Why Does “=” Mean Assignment? by macintux on Wednesday April 11, 2018 @09:09AM (#16810708)
The other responses captured the essence of what it is, but I thought it might be interesting to briefly discuss how Erlang uses it. As someone who hasn't been able to use Erlang in his day job for a year now, I sorely miss the language.

In nearly every other language, when you call a function, the top of the function typically involves a fair bit of analysis of the arguments to decide what needs to be done.

(That's being generous: typically the entire body of the function revolves around making decisions about what to do, such that you don't know what's going to come out of the function until you've traversed multiple branch options.)

In well-written Erlang, the function itself branches at the top, taking advantage of pattern matching, destructuring, and function heads.

Let's say you're passing around arbitrary data in the form of a tuple that you need to display. Or not, depending on the value of some debug flag.

In Python you might see code like this, assuming that an integer is stored in your program like ('int', 3) and a string might have some arbitrary label, so it's ('str', 'label', 'real string'):

  if (debug):
    display(x)
  
  def display(x):
    if (x[0] == 'int'):
      display_int(x[1])
    elif (x[0] == 'str'):
      display_string(x[1], x[2])
  
In Erlang, you can branch and destructure at the function head. You don't check the debug flag in the calling code, just pass it along for the function to decide what to do with it; if the flag is false, the function just returns false. (Variables in Erlang are capitalized; the lower-case "strings" in this code are atoms, also called symbols in some languages.)

  display(_, false) ->
    false;
  display({int, N}, _) ->
    display_int(N);
  display({str, Label, String}, _) ->
    display_string(Label, String).
Since you can choose the key data elements in your function arguments and branch accordingly in the function head, it becomes immediately obvious looking at the code how many different ways the code can evaluate, and the destructuring in the function heads means you don't have to waste code chunking the data apart before working with it.

(Updated: forgot to include the debug flag in the 2nd and 3rd function heads. In all 3 heads, the _ pseudo-variable basically says "I don't care what value we have here". Another option would be to use _Debug in the 2nd and 3rd heads to indicate to the reader what the flag is, or use true since we're expecting that value.)

Re:Why Does “=” Mean Assignment? by macintux on Wednesday April 11, 2018 @09:14AM (#16810751)
(Incidentally, Python used to allow tuples to be destructured in the function head, but they dropped it in Python 3 because no one knew about it or used it. A sad day.)
Re:Why Does “=” Mean Assignment? by mazesc on Wednesday April 11, 2018 @07:07AM (#16809862)
I could imagine by destructuring he means e.g. unapply in Scala: https://docs.scala-lang.org/tour/extractor-objects.html
Re:Why Does “=” Mean Assignment? by bogomipz on Wednesday April 11, 2018 @10:04AM (#16811159)
Ah OK its a functional construct, this make sense. I have seen this in my brief exposure to Clojure. Thanks for the examples and links.
Re:Why Does “=” Mean Assignment? by fiddlerwoaroof on Wednesday April 11, 2018 @11:49AM (#16812326)
Recent JS versions have it too:

    > let {a,b} = {a: 1, b: 2}
    > a
    1
    > b
    2