Smalltalk : best to avoid non-local returns? Algorithm rewrite - algorithm

This method (from SOM benchmarks) relies on Smalltalk non local returns. Is there a way to produce the same results without them?
placeQueenNonLocalReturn: c
1 to: 8 do: [ :r |
(self row: r column: c)
ifTrue: [
queenRows at: r put: c.
self row: r column: c put: false.
(c = 8) ifTrue: [ ^true ].
(self placeQueen: c + 1) ifTrue: [ ^true ].
self row: r column: c put: true ] ].
^false
!
Note (another question but related): Is it possible to change this code without knowing anything about callers and callees? I guess it should give a better understanding of purpose, but should not the method be self contained regarding my question?

Yes, it is possible.
You are using the non-local return only to get a quick exit from the 1 to: 8 do: loop.
You can easily write the loop with other syntax, like:
exit := false.
row := 1.
[row < 9 andNot: [exit]] whileTrue: [ (self row: r column: c)
ifTrue: [
queenRows at: r put: c.
self row: r column: c put: false.
c = 8 ifTrue: [ exit := true ]
ifFalse: [ (self placeQueen: c + 1)
ifTrue: [ exit := true ]
ifFalse: [self row: r column: c put: true ] ] ].
^exit
Note that the call to placeQueen: in the loop seems to be recursive, may be the selector of your method is wrong.
I don´t understand what do you mean with "knowing about callers and callees"... I did a mostly syntactic rewrite on the code.
Same about the self-containment.
This method is not self-contained, it seems to be part of the 8 Queen problem solution, but relies on (self row: r column: c) to check the validity of a place for a new queen.

Let's correct a misunderstanding. The code as shown does not contain any non-local returns, so it cannot be relying on this feature.
The returns shown are are all just normal returns - they return a result back to the caller.
A non-local return refers to the case where a value is returned to somewhere other than the calling method.
So there is no reason to avoid the returns shown,

Related

Argument in fuction call inside function definition is not being replaced in Maxima

The problem
Consider the following script written in Maxima
$ cat main.max
foo(a) ::= block(
if a = 0 then return(0) else return(1)
)$
bar(a) ::= block(
return(foo(a))
)$
foo(0);
bar(0);
Executing this script yields to
$ cat main.max | maxima --very-quiet
0
1
The question
Isn't it supposed that calling foo by itself results the same as if it is called from another function (in this scenario, bar)?
Here there is another example
$ cat main.max
foo(a) ::= block(disp(a))$
bar(a) ::= block(foo(a))$
foo(0)$
bar(0)$
$ cat main.max | maxima --very-quiet
0
a
In other words: Why isn't maxima replacing the argument that is passed to bar in the foo function call which is located within bar?
Additional context
This is the version that I'm currently using
$ maxima --version
Maxima 5.43.2
::= defines a function which quotes (does not evaluate) its arguments, and the return value of the function is evaluated by the caller. Such a function is conventionally called a "macro" for historical reasons.
I think you want an ordinary, argument-evaluating function, which is defined by :=. Try substituting := for ::= in your function definitions -- when I try that, I get 0 for bar(0) as expected.
Macros are useful, but in relatively narrow circumstances. I think ordinary functions are much more common than macros.
As an aside, in the functions which you have shown, block and return are unneeded. My advice is to just leave them out and make the functions more succinct and therefore more clear. E.g.
foo(a) := if a = 0 then 0 else 1;
bar(a) := foo(a);
Finally, note that = is only literal comparison, not equivalence; equivalence is tested with equal. E.g. suppose x is not otherwise defined. Then is(x = 0) yields false, but is(equal(x, 0)) yields the expression equal(x, 0). Depending on what you're doing, one or the other might be appropriate.

'==' type and pattern matching - wait for the other recursive calls and do nothing on a case

I have two questions concerning OCaml.
Firstly, what does the == means when defining a type.
For example you can see at the end of this page the following code:
type compteur == int;;
Then what is the difference with:
type compteur = int;;
Moreover I have an other question concerning pattern matching.
How to say that you want to return nothing on a case.
For example let's say I have a function f that returns a boolean:
let rec f v = function
| t when t<v -> true
| t when t > v -> f (t-1)
| t when t = v -> (* here a code to say that you do nothing, and wait for the other recursive call *)
type compteur == int is a syntax error. The only valid way to define a type alias is with =, not ==. It's just a typo on the page you linked.
How to say that you want to return nothing on a case.
The only way to return nothing from a function would be to exit the program, raise an exception or loop (or recur) infinitely. Otherwise a function always returns a value.
here a code to say that you do nothing, and wait for the other recursive call
What other recursive call? In the case that t = v only the code for that case will run. There is no other code to wait on.

Binding vs Assignment

I've read a number of articles on the difference between assignment and binding, but it hasn't clicked yet (specifically in the context of an imperative language vs one without mutation).
I asked in IRC, and someone mentioned these 2 examples illustrate the difference, but then I had to go and I didn't see the full explanation.
Can someone please explain how/why this works in a detailed way, to help illustrate the difference?
Ruby
x = 1; f = lambda { x }; x = 2; f.call
#=> 2
Elixir
x = 1; f = fn -> x end; x = 2; f.()
#=> 1
I've heard this explanation before and it seems pretty good:
You can think of binding as a label on a suitcase, and assignment as a
suitcase.
In other languages, where you have assignment, it is more like putting a value in a suitcase. You actually change value that is in the suitcase and put in a different value.
If you have a suitcase with a value in it, in Elixir, you put a label on it. You can change the label, but the value in the suitcase is still the same.
So, for example with:
iex(1)> x = 1
iex(2)> f = fn -> x end
iex(3)> x = 2
iex(4)> f.()
1
You have a suitcase with 1 in it and you label it x.
Then you say, "Here, Mr. Function, I want you to tell me what is in this suitcase when I call you."
Then, you take the label off of the suitcase with 1 in it and put it on another suitcase with 2 in it.
Then you say "Hey, Mr. Function, what is in that suitcase?"
He will say "1", because the suitcase hasn't changed. Although, you have taken your label off of it and put it on a different suitcase.
After a while, I came up with the answer that is probably the best explanation of the difference between “binding” and “assignment”; it has nothing in common with what I have written in another answer, hence it’s posted as a separate answer.
In any functional language, where everything is immutable, there is no meaningful difference between terms “binding” and “assignment.” One might call it either way; the common pattern is to use the word “binding,“ explicitly denoting that it’s a value bound to a variable. In Erlang, for instance, one can not rebound a variable. In Elixir this is possible (why, for God’s sake, José, what for?)
Consider the following example in Elixir:
iex> x = 1
iex> 1 = x
The above is perfectly valid Elixir code. It is evident, one cannot assign anything to one. It is neither assignment nor binding. It is matching. That is how = is treated in Elixir (and in Erlang): a = b fails if both are bound to different values; it returns RHO if they match; it binds LHO to RHO if LHO is not bound yet.
In Ruby it differs. There is a significant difference between assignment (copying the content,) and binding (making a reference.)
Elixir vs Ruby might not be the best contrast for this. In Elixir, we can readily "re-assign" the value of a previously assigned named variable. The two anonymous-function examples you provided demonstrate the difference in how the two languages assign local variables in them. In Ruby, the variable, meaning the memory reference, is assigned, which is why when we change it, the anonymous function returns the current value stored in that memory-reference. While in Elixir, the value of the variable at the time the anonymous function is defined (rather than the memory reference) is copied and stored as the local variable.
In Erlang, Elixir's "parent" language, however, variables as a rule are "bound." Once you've declared the value for the variable named X, you are not allowed to alter it for the remainder of the program and any needed alterations would need to be stored in new named variables. (There is a way to reassign a named variable in Erlang but it is not the custom.)
Binding refers to particular concept used in expression-based languages that may seem foreign if you're used to statement-based languages. I'll use an ML-style example to demonstrate:
let x = 3 in
let y = 5 in
x + y
val it : int = 8
The let... in syntax used here demonstrates that the binding let x = 3 is scoped only to the expression following the in. Likewise, the binding let y = 5 is only scoped to the expression x + y, such that, if we consider another example:
let x = 3 in
let f () =
x + 5
let x = 4 in
f()
val it : int = 8
The result is still 8, even though we have the binding let x = 4 above the call to f(). This is because f itself was bound in the scope of the binding let x = 3.
Assignment in statement-based languages is different, because the variables being assigned are not scoped to a particular expression, they are effectively 'global' for whatever block of code they're in, so reassigning the value of a variable changes the result of an evaluation that uses the same variable.
The easiest way to understand the difference, would be to compare the AST that is used by the language interpreter/compiler to produce machine-/byte-code.
Let’s start with ruby. Ruby does not provide the AST viewer out of the box, so I will use RubyParser gem for that:
> require 'ruby_parser'
> RubyParser.new.parse("x = 1; f = -> {x}; x = 2; f.()").inspect
#=> "s(:block, s(:lasgn, :x, s(:lit, 1)),
# s(:lasgn, :f, s(:iter, s(:call, nil, :lambda), 0, s(:lvar, :x))),
# s(:lasgn, :x, s(:lit, 2)), s(:call, s(:lvar, :f), :call))"
The thing we are looking for is the latest node in the second line: there is x variable inside the proc. In other words, ruby expects the bound variable there, named x. At the time the proc is evaluated, x has a value of 2. Hence the the proc returns 2.
Let’s now check Elixir.
iex|1 ▶ quote do
...|1 ▶ x = 1
...|1 ▶ f = fn -> x end
...|1 ▶ x = 2
...|1 ▶ f.()
...|1 ▶ end
#⇒ {:__block__, [],
# [
# {:=, [], [{:x, [], Elixir}, 1]},
# {:=, [], [{:f, [], Elixir}, {:fn, [], [{:->, [], [[], {:x, [], Elixir}]}]}]},
# {:=, [], [{:x, [], Elixir}, 2]},
# {{:., [], [{:f, [], Elixir}]}, [], []}
# ]}
Last node in the second line is ours. It still contains x, but during a compilation stage this x will be evaluated to it’s currently assigned value. That said, fn -> not_x end will result in compilation error, while in ruby there could be literally anything inside a proc body, since it’ll be evaluated when called.
In other words, Ruby uses a current caller’s context to evaluate proc, while Elixir uses a closure. It grabs the context it encountered the function definition and uses it to resolve all the local variables.

How are 'bind' and 'in' different?

Take the following code which creates a context:
c: context [a: 2]
You can see it creates a context c, and that a is not bound in the global context:
>> ?? c
c: make object! [
a: 2
]
>> a
** Script Error: a has no value
** Near: a
Now if you use bind 'a c, it returns the value of the word in the context it was bound:
>> get bind 'a c
== 2
Which is also the same as in c 'a:
>> (get bind 'a c) = (get in c 'a)
== true
Looks like in is a version of bind with flipped arguments
So, how is in different?
There are some obvious feature additions in bind, like having a refinement /copy for efficiency, and also accepting a block! instead of a single word for its words argument.
In which case, the question becomes, why in?
Note
This was initially motivated by comments in this question, when I didn't quite understood what bind does, and a discussion on gitter prompted me to post this
The big difference is that BIND can propagate the context of a word:
>> q: func [/local a b][a: 1 b: 2 return 'a]
>> get bind 'b q
== 2
>> get in q 'b
** Script Error: in expected object argument of type: object port
** Near: get in q 'b
Rebol 2 only of course.

How to I set a ruby variable based on an if-then decision tree

I want to write the following:
variable = if x
a
else
if y
b
else
c
end
end
Where if x is true, variable equals a. If x is false and y is true, variable equals b. If x and y are both false, variable equals c.
I thought this was valid ruby syntax but when I try it, the variable is always set to nil. Why is this and how do I set it correctly?
I am using ruby 1.9.3 btw
Edit: FALSE ALARM. In my example, c was set to nil which I thought was erroneous. My original syntax worked fine. I'm not sure of the StackOverflow etiquette on whether I should delete this question, advise is welcome.
Thanks for the quick responses.
Do not make it complicated! There is nothing wrong with writing
variable =
if x then a
elsif y then b
else c
end
No one will look at this code and not figure out what has happend.
There two main variants:
With a if-else-end tree:
variable =
if x
a
else
if y
b
else
c
end
end
and as a logical boolean algebra expression:
variable = x && a || ( y && b || c )
That is the same as:
variable = x && a || y && b || c
The first variant is usually preferred, then you are using complex code or calculation inside the if-else-end blocks. The second, when the simple read/logical constructions is used.
If you have an error or get an invalid result in your expression, just check your logical expression.

Resources