Override '+' in smalltalk, to accept two parameters? - smalltalk

Is it possible to override the + operator in smalltalk to accept two params? i.e., I need to also pass in the units for my custom class. Something like:
Number subclass: #NumberWithUnits
instanceVariableNames: 'myName unitTracker'
classVariableNames: ''
poolDictionaries: ''
category: 'hw3'
+ aNumber theUnits
unitTracker adjustUnits: theUnits.
^super + aNumber
Or is there an easier way to do this that I haven't considered?
Additional problem description:
(NumberWithUnits value: 3 unit: #seconds) should give you a NumberWithUnits that represents 3 seconds. But you should also be able to write 3 sec and that should evaluate to a NumberWithUnits (seconds is already taken in Pharo 2.0). The way to do this is to add a sec method to Number, which basically returns (NumberWithUnits value: self unit: #seconds). You can add methods for meters and elephants as well. Then you could write an expression 3 elephants / (1 sec sec) and it would return the right thing. Write a test for it to be sure!

What you're missing is the order of evaluation/precedence in Smalltalk. It's actually quite a bit simpler than in most other languages:
explicit parentheses ()
unary
binary
keyword
assignment :=
So, you can implement a unary method on Number which gets evaluated before the binary +. A simple example is Number>>negated, which is Smalltalk's version of the unary minus.
At least in Squeak/Pharo (all I've got handy at the moment), date arithmetic is already implemented similarly. Look at Number>>minutes, for example, so you can evaluate things like 5 hours - 3 minutes, which returns a Duration of 0:04:57:00.

I think a more idiomatic way to do this would be to construct a second NumberWithUnits, and then add that.
Then inside your + method you need to reconcile the units of the two things being added, then add their magnitudes.
So something like
a := Measure new: 2 #m
b := Measure new: 10 #mm
a + b
Measure class [
+ other [
"TODO: check/convert units here"
resultMagnitude := (a magnitude) + (b magnitude).
combinedUnits := (a units) * (b units).
^Measure new resultMagnitude units: combinedUnits.
]
]
See also for example the GNU Smalltalk example of operator overloading.

Related

How to generate a lazy division?

I want to generate the sequence of
1, 1/2, 1/3, 1/4 ... *
using functional programming approach in raku, in my head it's should be look like:
(1,{1/$_} ...*)[0..5]
but the the output is: 1,1,1,1,1
The idea is simple, but seems enough powerful for me to using to generate for other complex list and work with it.
Others things that i tried are using a lazy list to call inside other lazy list, it doesn't work either, because the output is a repetitive sequence: 1, 0.5, 1, 0.5 ...
my list = 0 ... *;
(1, {1/#list[$_]} ...*)[0..5]
See #wamba's wonderful answer for solutions to the question in your title. They showcase a wide range of applicable Raku constructs.
This answer focuses on Raku's sequence operator (...), and the details in the body of your question, explaining what went wrong in your attempts, and explaining some working sequences.
TL;DR
The value of the Nth term is 1 / N.
# Generator ignoring prior terms, incrementing an N stored in the generator:
{ 1 / ++$ } ... * # idiomatic
{ state $N; $N++; 1 / $N } ... * # longhand
# Generator extracting denominator from prior term and adding 1 to get N:
1/1, 1/2, 1/3, 1/(*.denominator+1) ... * # idiomatic (#jjmerelo++)
1/1, 1/2, 1/3, {1/(.denominator+1)} ... * # longhand (#user0721090601++)
What's wrong with {1/$_}?
1, 1/2, 1/3, 1/4 ... *
What is the value of the Nth term? It's 1/N.
1, {1/$_} ...*
What is the value of the Nth term? It's 1/$_.
$_ is a generic parameter/argument/operand analogous to the English pronoun "it".
Is it set to N?
No.
So your generator (lambda/function) doesn't encode the sequence you're trying to reproduce.
What is $_ set to?
Within a function, $_ is bound either to (Any), or to an argument passed to the function.
If a function explicitly specifies its parameters (a "parameter" specifies an argument that a function expects to receive; this is distinct from the argument that a function actually ends up getting for any given call), then $_ is bound, or not bound, per that specification.
If a function does not explicitly specify its parameters -- and yours doesn't -- then $_ is bound to the argument, if any, that is passed as part of the call of the function.
For a generator function, any value(s) passed as arguments are values of preceding terms in the sequence.
Given that your generator doesn't explicitly specify its parameters, the immediately prior term, if any, is passed and bound to $_.
In the first call of your generator, when 1/$_ gets evaluated, the $_ is bound to the 1 from the first term. So the second term is 1/1, i.e. 1.
Thus the second call, producing the third term, has the same result. So you get an infinite sequence of 1s.
What's wrong with {1/#list[$_+1]}?
For your last example you presumably meant:
my #list = 0 ... *;
(1, {1/#list[$_+1]} ...*)[0..5]
In this case the first call of the generator returns 1/#list[1+1] which is 1/2 (0.5).
So the second call is 1/#list[0.5+1]. This specifies a fractional index into #list, asking for the 1.5th element. Indexes into standard Positionals are rounded down to the nearest integer. So 1.5 is rounded down to 1. And #list[1] evaluates to 1. So the value returned by the second call of the generator is back to 1.
Thus the sequence alternates between 1 and 0.5.
What arguments are passed to a generator?
Raku passes the value of zero or more prior terms in the sequence as the arguments to the generator.
How many? Well, a generator is an ordinary Raku lambda/function. Raku uses the implicit or explicit declaration of parameters to determine how many arguments to pass.
For example, in:
{42} ... * # 42 42 42 ...
the lambda doesn't declare what parameters it has. For such functions Raku presumes a signature including $_?, and thus passes the prior term, if any. (The above lambda ignores it.)
Which arguments do you need/want your generator to be passed?
One could argue that, for the sequence you're aiming to generate, you don't need/want to pass any of the prior terms. Because, arguably, none of them really matter.
From this perspective all that matters is that the Nth term computes 1/N. That is, its value is independent of the values of prior terms and just dependent on counting the number of calls.
State solutions such as {1/++$}
One way to compute this is something like:
{ state $N; $N++; 1/$N } ... *
The lambda ignores the previous term. The net result is just the desired 1 1/2 1/3 ....
(Except that you'll have to fiddle with the stringification because by default it'll use gist which will turn the 1/3 into 0.333333 or similar.)
Or, more succinctly/idiomatically:
{ 1 / ++$ } ... *
(An anonymous $ in a statement/expression is a simultaneous declaration and use of an anonymous state scalar variable.)
Solutions using the prior term
As #user0721090601++ notes in a comment below, one can write a generator that makes use of the prior value:
1/1, 1/2, 1/3, {1/(.denominator+1)} ... *
For a generator that doesn't explicitly specify its parameters, Raku passes the value of the prior term in the sequence as the argument, binding it to the "it" argument $_.
And given that there's no explicit invocant for .denominator, Raku presumes you mean to call the method on $_.
As #jjmerelo++ notes, an idiomatic way to express many lambdas is to use the explicit pronoun "whatever" instead of "it" (implicit or explicit) to form a WhateverCode lambda:
1/1, 1/2, 1/3, 1/(*.denominator+1) ... *
You drop the braces for this form, which is one of its advantages. (You can also use multiple "whatevers" in a single expression rather than just one "it", another part of this construct's charm.)
This construct typically takes some getting used to; perhaps the biggest hurdle is that a * must be combined with a "WhateverCodeable" operator/function for it to form a WhateverCode lambda.
TIMTOWTDI
routine map
(1..*).map: 1/*
List repetition operator xx
1/++$ xx *
The cross metaoperator, X or the zip metaoperator Z
1 X/ 1..*
1 xx * Z/ 1..*
(Control flow) control flow gather take
gather for 1..* { take 1/$_ }
(Seq) method from-loop
Seq.from-loop: { 1/++$ }
(Operators) infix ...
1, 1/(1+1/*) ... *
{1/++$} ... *

Can one create a standalone method/function (without any class)

I am trying to understand smalltalk. Is it possible to have a standalone method/function, which is not part of any particular class, and which can be called later:
amethod ['amethod called' printNl].
amethod.
Above code gives following error:
simpleclass.st:1: expected Eval, Namespace or class definition
How can I use Eval or Namespace as being suggested by error message?
I tried following but none work:
Eval amethod [...
amethod Eval [...
Eval amethod Eval[... "!"
Eval [... works but I want to give a name to the block so that I can call it later.
Following also works but gets executed immediately and does not execute when called later.
Namespace current: amethod ['amethod called' printNl].
Thanks for your insight.
In Smalltalk the equivalent to a standalone method is a Block (a.k.a. BlockClosure). You create them by enclosing Smalltalk expressions between square brackets. For example
[3 + 4]
To evaluate a block, you send it the message value:
[3 + 4] value
which will answer with 7.
Blocks may also have arguments:
[:s | 3 + s]
you evaluate them with value:
[:s | 3 + s] value: 4 "answers with 7"
If the block has several sentences, you separate them with a dot, as you would do in the body of a method.
Addendum
Blocks in Smalltalk are first class objects. In particular, one can reference them with variables, the same one does with any other objects:
three := 3.
threePlus := [:s | three + s].
for later use
threePlus value: 4 "7"
Blocks can be nested:
random := Random new.
compare := [:p :u | u <= p]
bernoulli60 := [compare value: 0.6 value: random next].
Then the sequence:
bernoulli60 value. "true"
bernoulli60 value. "false"
...
bernoulli60 value. "true"
will answer with true about 60% of the times.
Leandro's answer, altough being correct and with deep smalltalk understanding, is answering what you asked for, but I think, not 100% sure thou, you are actually asking how to "play" around with a code without the need to create a class.
In my eyes want you want is called a Workspace (Smalltalk/X and Dolphin) (it can have different names like Playground in Pharo Smalltalk).
If you want to play around you need to create a local variable.
| result |
result := 0. "Init otherwise nil"
"Adding results of a simple integer factorial"
1 to: 10 do: [ :integer |
result := result + integer factorial
].
Transcript show: result.
Explanation:
I'm using a do: block for 1-10 iterration. (:integer is a block local variable). Next I'm, showing the result on Transcript.

Does Perl 6 have an infinite Int?

I had a task where I wanted to find the closest string to a target (so, edit distance) without generating them all at the same time. I figured I'd use the high water mark technique (low, I guess) while initializing the closest edit distance to Inf so that any edit distance is closer:
use Text::Levenshtein;
my #strings = < Amelia Fred Barney Gilligan >;
for #strings {
put "$_ is closest so far: { longest( 'Camelia', $_ ) }";
}
sub longest ( Str:D $target, Str:D $string ) {
state Int $closest-so-far = Inf;
state Str:D $closest-string = '';
if distance( $target, $string ) < $closest-so-far {
$closest-so-far = $string.chars;
$closest-string = $string;
return True;
}
return False;
}
However, Inf is a Num so I can't do that:
Type check failed in assignment to $closest-so-far; expected Int but got Num (Inf)
I could make the constraint a Num and coerce to that:
state Num $closest-so-far = Inf;
...
$closest-so-far = $string.chars.Num;
However, this seems quite unnatural. And, since Num and Int aren't related, I can't have a constraint like Int(Num). I only really care about this for the first value. It's easy to set that to something sufficiently high (such as the length of the longest string), but I wanted something more pure.
Is there something I'm missing? I would have thought that any numbery thing could have a special value that was greater (or less than) all the other values. Polymorphism and all that.
{new intro that's hopefully better than the unhelpful/misleading original one}
#CarlMäsak, in a comment he wrote below this answer after my first version of it:
Last time I talked to Larry about this {in 2014}, his rationale seemed to be that ... Inf should work for all of Int, Num and Str
(The first version of my answer began with a "recollection" that I've concluded was at least unhelpful and plausibly an entirely false memory.)
In my research in response to Carl's comment, I did find one related gem in #perl6-dev in 2016 when Larry wrote:
then our policy could be, if you want an Int that supports ±Inf and NaN, use Rat instead
in other words, don't make Rat consistent with Int, make it consistent with Num
Larry wrote this post 6.c. I don't recall seeing anything like it discussed for 6.d.
{and now back to the rest of my first answer}
Num in P6 implements the IEEE 754 floating point number type. Per the IEEE spec this type must support several concrete values that are reserved to stand in for abstract concepts, including the concept of positive infinity. P6 binds the corresponding concrete value to the term Inf.
Given that this concrete value denoting infinity already existed, it became a language wide general purpose concrete value denoting infinity for cases that don't involve floating point numbers such as conveying infinity in string and list functions.
The solution to your problem that I propose below is to use a where clause via a subset.
A where clause allows one to specify run-time assignment/binding "typechecks". I quote "typecheck" because it's the most powerful form of check possible -- it's computationally universal and literally checks the actual run-time value (rather than a statically typed view of what that value can be). This means they're slower and run-time, not compile-time, but it also makes them way more powerful (not to mention way easier to express) than even dependent types which are a relatively cutting edge feature that those who are into advanced statically type-checked languages tend to claim as only available in their own world1 and which are intended to "prevent bugs by allowing extremely expressive types" (but good luck with figuring out how to express them... ;)).
A subset declaration can include a where clause. This allows you to name the check and use it as a named type constraint.
So, you can use these two features to get what you want:
subset Int-or-Inf where Int:D | Inf;
Now just use that subset as a type:
my Int-or-Inf $foo; # ($foo contains `Int-or-Inf` type object)
$foo = 99999999999; # works
$foo = Inf; # works
$foo = Int-or-Inf; # works
$foo = Int; # typecheck failure
$foo = 'a'; # typecheck failure
1. See Does Perl 6 support dependent types? and it seems the rough consensus is no.

When can I use the Whatever star?

Following this post on perlgeek, it gives an example of currying:
my &add_two := * + 2;
say add_two(5); # 7
Makes sense. But if I swap the + infix operator for the min infix operator:
my &min_two := * min 2;
say min_two(5); # Type check failed in binding; expected 'Callable' but got 'Int'
Even trying to call + via the infix syntax fails:
>> my &curry := &infix:<+>(2, *);
Method 'Int' not found for invocant of class 'Whatever'
Do I need to qualify the Whatever as a numeric value, and if so how? Or am I missing the point entirely?
[Edited with responses from newer rakudo; Version string for above: perl6 version 2014.08 built on MoarVM version 2014.08]
Your Rakudo version is somewhat ancient. If you want to use a more recent cygwin version, you'll probably have to compile it yourself. If you're fine with the Windows version, you can get a binary from rakudo.org.
That said, the current version also does not transform * min 2 into a lambda, but from a cursory test, seems to treat the * like Inf. My Perl6-fu is too weak to know if this is per spec, or a bug.
As a workaround, use
my &min_two := { $_ min 2 };
Note that * only auto-curries (or rather 'auto-primes' in Perl6-speak - see S02) with operators, not function calls, ie your 3rd example should be written as
my &curry := &infix:<+>.assuming(2);
This is because the meaning of the Whatever-* depends on context: it is supposed to DWIM.
In case of function calls, it gets passed as an argument to let the callee decide what it wants to do with it. Even operators are free to handle Whatever explicitly (eg 1..*) - but if they don't, a Whatever operand transforms the operation into a 'primed' closure.

Why does 22 when converted to a string, with printOn or StoreOn, still add like an integer?

This is my code:
x := 22 storeString.
y := x + x.
Transcript show: y.
Expected output: 2222
Actual output: 44.
I thought that the storeString message, sent to 22, assigned to x, would result in a string value being stored into x.
So I thought, I'm pretty new in smalltalk. Maybe it's order of operations? So I tried this:
x := (22 storeString).
y := x + x.
Transcript show: y.
Same result, and same, if I use printOn instead of storeOn. This is probably a day-one tutorial-following type question. But what is going on? Note that I know about the concatenation operator (,) but I am still wondering how it is that you can add two strings together like this? Is some implicit conversion from string back to integer happening as part of +?
Only a few things are implicit in Smalltalk. You can browse the implementation of #+ selector in String class and find out yourself what is going on. Or print String >> #+ definition.
You can also check out the internals of any running object instance, so you could have evaluated x inspect, to find out that x really is a String.
#+ is implemented on String and does a coercion to a Number before doing the addition.
Squeak has lot of eToys (a Smalltalk variation for kids) code spread throughout its core codebase. This is likely the reason why String implements all math operators. In Pharo the math operators have been mostly removed from String, so '1' + '2' raises an error like in any other Smalltalk.
Open a workspace. Enter:
'12' + '34'
Highlight and then use the right button menu to invoke "debug it". If ever there was a "killer app" for Smalltlak, it is the way the Smalltalk debugger interacts with the "all objects all the time" nature of Smalltalk. You can see what everything is and how it does. If you use "into", you'll be able to see exactly how it pulls off turning that into '46'.
Even cooler (I think), is that you can do
12 + '34'
(the first is no longer a string, rather a direct number). Again, you can use the debugger, and the whole double dispatch mechanism Smalltalk uses to do transcendental math will be opened up to you.
You can even do weirder examples like
4.0 + #('13' 2)
(here we're adding a number to an array, and the array contents are of mixed type)
Happy Smalltalking!
this behavior may appear puzzling to anyone not familiar with smalltalk, especially since in other languages the exact opposite tends to happen (numbers are coerced to strings).
the reason why this not a problem, is because string concatenation is done with ,. once aware of that, it becomes clear that '22' + 22 or even '22' + '22' can never be '2222'. it's either going to fail, or produce 44.
so if string concatenation is what you want, you need to send the right message:
x := 22 storeString.
y := x , x.
Transcript show: y.