Not able to create instance of object - object

I am just starting to use gnu-smalltalk. I have taken following code from here to define a class:
Number subclass: Complex [
| realpart imagpart |
"This is a quick way to define class-side methods."
Complex class >> new [
<category: 'instance creation'>
^self error: 'use real:imaginary:'
]
Complex class >> new: ignore [
<category: 'instance creation'>
^self new
]
Complex class >> real: r imaginary: i [
<category: 'instance creation'>
^(super new) setReal: r setImag: i
]
setReal: r setImag: i [ "What is this method with 2 names?"
<category: 'basic'>
realpart := r.
imagpart := i.
^self
]
]
However, I am not able to create any instances of this class. I have tried various methods and following gives least error!
cn := Complex new: real:15 imaginary:25
cn printNl
The error is:
complexNumber.st:24: expected object
Mostly the error is as follows, e.g. if there is no colon after new keyword:
$ gst complexNumber.st
Object: Complex error: use real:imaginary:
Error(Exception)>>signal (ExcHandling.st:254)
Error(Exception)>>signal: (ExcHandling.st:264)
Complex class(Object)>>error: (SysExcept.st:1456)
Complex class>>new (complexNumber.st:7)
UndefinedObject>>executeStatements (complexNumber.st:25)
nil
Also, I am not clear what is this method with 2 names, each with one argument:
setReal: r setImag: i [ "How can there be 2 names and arguments for one method/function?"
<category: 'basic'>
realpart := r.
imagpart := i.
^self
]
I believe usual method should be with one name and argument(s), as from code here :
spend: amount [
<category: 'moving money'>
balance := balance - amount
]

To create the Complex number 25 + 25i evaluate
Complex real: 25 imaginary: 25
How do I know? Because the first part of your question reads
Complex class >> real: r imaginary: i [
<category: 'instance creation'>
^(super new) setReal: r setImag: i
]
Your mistake was to write Complex new: real: 25 imaginary: 25, which doesn't conform to the Smalltalk syntax.
The Smalltalk syntax for a message with, say, 2 (or more) arguments consists of 2 (or more) keywords, ending with colon, followed, each of them, by the corresponding argument.
For example, the method setReal: r setImag: i has two keywords, namely setReal: and setImag: and receives two arguments r and i. The name of the method, which in Smalltalk is called its selector is the Symbol that results from concatenating the keywords, in this case setReal:setImag:.

Related

VHDL Type Attribute

I have found these lines in mathpack.vhd:
constant TWO_AT_MINUS : REAL_VECTOR := POWER_OF_2_SERIES(
NATURAL_VECTOR'(100, 90),1.0,
MAX_ITER);
The signature of the POWER_OF_2_SERIES is in the same file:
function POWER_OF_2_SERIES (D : in NATURAL_VECTOR; INITIAL_VALUE : in REAL;
NUMBER_OF_VALUES : in NATURAL) return REAL_VECTOR is
So it's clear that NATURAL_VECTOR'(100, 90) produces a NATURAL_VECTOR, but how?I have never seen something like it and I can't find it in the LRM. Can anybody elaborate on this notation/where I can find it in the LRM?
Found it... it is a qualified expression for an aggregate (LRM 7.3.4) defined as
qualified_expression ::=
type_mark ' ( expression )
| type_mark ' aggregate
and as choices are optional in an aggregate (LRM 7.3.2)
aggregate ::=
( element_association { , element_association } )
element_association ::=
[ choices => ] expression
this is simply a one dimensional array containing the two values 100 and 90 and as
type NATURAL_VECTOR is array (NATURAL range <>) of NATURAL;
I would assume that they are in 0 => 100 and 1 => 90, modelSim thinks so, too.

Why does Haskell not accept this syntax for lists?

Consider the following code snippet in Idris:
myList : List Int
myList = [
1,
2,
3
]
The closing delimiter ] is on the same column as the declaration itself. I find this a quite natural way to want to format long, multi-line lists.
However, the equivalent snippet in Haskell fails to compile with a syntax error:
myList :: [Int]
myList = [
1,
2,
3
]
>> main.hs:9:1: error:
>> parse error (possibly incorrect indentation or mismatched brackets)?
>> |
>> 9 | ]
>> | ^
And requires instead the the closing delimiter ] is placed on a column number strictly greater than where the expression is declared. Or at least, as far as I can garner, this seems to be what is going on.
Is there a reason Haskell doesn't like this syntax? I know there are some subtle interactions between the Haskell parser and lexer to enable Haskell's implementation of the offsides rule, so perhaps it has something to do with that.
Well, ultimately the answer is just “because the Haskell language standard demands it to be parsed this way”.
As to for some reasoning why this is a good idea, it's that indentation is the primary way code is structured, and parentheses/brackets only come in locally. I find this much more consequent than Python's attitude that indentation is kind of the primary structure, but for an expression to spread over multiple lines you actually need to wrap it in parentheses. (Not saying that these are the only two ways it could be done.)
Note that if you really want, you can always disable the indentation sensitivity completely, with something like
myList :: [Int]
myList = l where {
l = [
1,
2,
3
]}
But I would not recommend it. The preferred style to write multiline lists is
myList
= [ 1
, 2
, 3
]
or
myList = [ 1
, 2
, 3 ]
Again, I would argue that this leading-comma style is much preferrable to the trailing-comma one most programmers in other languages use, especially for nested lists: the commas become “bullet points” aligned with the opening bracket, which makes the AST structure very clear.
myMonstrosity :: [(Int, [([Int], Int)])]
= [ ( 1
, [ ( [37,43]
, 9 )
, ( [768,4,9807,3,4,98]
, 15 ) ]
)
, ( 2, [] )
, ( 3
, [ ( [], 300 )
, ( [0..4000], -5 ) ]
)
]

Indices of a substring in Smalltalk

It seems Smalltalk implementations misses an algorithm which return all the indices of a substring in a String. The most similar ones returns only one index of an element, for example : firstIndexesOf:in: , findSubstring:, findAnySubstring: variants.
There are implementations in Ruby but the first one relies on a Ruby hack, the second one does not work ignoring overlapping Strings and the last one uses an Enumerator class which I don't know how to translate to Smalltalk. I wonder if this Python implementation is the best path to start since considers both cases, overlapping or not and does not uses regular expressions.
My goal is to find a package or method which provides the following behavior:
'ABDCDEFBDAC' indicesOf: 'BD'. "#(2 8)"
When overlapping is considered:
'nnnn' indicesOf: 'nn' overlapping: true. "#(0 2)"
When overlapping is not considered:
'nnnn' indicesOf 'nn' overlapping: false. "#(0 1 2)"
In Pharo, when a text is selected in a Playground, a scanner detects the substring and highlights matches. However I couldn't find a String implementation of this.
My best effort so far results in this implementation in String (Pharo 6):
indicesOfSubstring: subString
| indices i |
indices := OrderedCollection new: self size.
i := 0.
[ (i := self findString: subString startingAt: i + 1) > 0 ] whileTrue: [
indices addLast: i ].
^ indices
Let me firstly clarify that Smalltalk collections are 1-based, not 0-based. Therefore your examples should read
'nnnn' indexesOf: 'nn' overlapping: false. "#(1 3)"
'nnnn' indexesOf: 'nn' overlapping: true. "#(1 2 3)"
Note that I've also taken notice of #lurker's observation (and have tweaked the selector too).
Now, starting from your code I would change it as follows:
indexesOfSubstring: subString overlapping: aBoolean
| n indexes i |
n := subString size.
indexes := OrderedCollection new. "removed the size"
i := 1. "1-based"
[
i := self findString: subString startingAt: i. "split condition"
i > 0]
whileTrue: [
indexes add: i. "add: = addLast:"
i := aBoolean ifTrue: [i + 1] ifFalse: [i + n]]. "new!"
^indexes
Make sure you write some few unit tests (and don't forget to exercise the border cases!)
Edited
It would also be nice if you would tell us what you need to achieve in the "greater picture". Sometimes Smalltalk offers different approaches.
Leandro beat me to the the code (and his code is more efficient), but I have already written it so I'll share it too. Heed his advice on Smalltalk being 1-based => rewritten example.
I have used Smalltalk/X and Pharo 6.1 for the example.
The code would be:
indexesOfSubstring: substringToFind overlapping: aBoolean
| substringPositions aPosition currentPosition |
substringPositions := OrderedSet new. "with overlap on you could get multiple same
positions in the result when there is more to find in the source string"
substringToFindSize := substringToFind size. "speed up for large strings"
aPosition := 1.
[ self size > aPosition ] whileTrue: [
currentPosition := self findString: substringToFind startingAt: aPosition.
(currentPosition = 0) ifTrue: [ aPosition := self size + 1 ] "ends the loop substringToFind is not found"
ifFalse: [
substringPositions add: currentPosition.
aBoolean ifTrue: [ aPosition := aPosition + 1 ] "overlapping is on"
ifFalse: [ aPosition := currentPosition + substringToFindSize ] "overlapping is off"
]
].
^ substringPositions
I have fixed some issues that occured to me. Don't forget to test it as much as you can!

Model a finite set of integers

Below is an Alloy model representing this set of integers: {0, 2, 4, 6}
As you know, the plus symbol (+) denotes set union. How can 0 be unioned to 2? 0 and 2 are not sets. I thought the union operator applies only to sets? Isn't this violating a basic notion of set union?
Second question: Is there a better way to model this, one that is less cognitively jarring?
one sig List {
numbers: set Int
} {
numbers = 0 + 2 + 4 + 6
}
In Alloy, everything you work with is a set of tuples. none is the empty set, and many sets are sets of relations (tuples with arity > 1). So also each integer, when you use it, is a set with a relation of arity 1 and cardinality 1. I.e. in Alloy when you use 1 it is really {(1)}, a set of a type containing the atom 1. I.e. the definition is in reality like:
enum Int {-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7}
Ints in Alloy are just not very good integers :-( The finite set of atoms is normally not a problem but with Ints there are just too few of them to be really useful. Worse, they quickly overflow and Alloy is not good in handling this at all.
But I do agree it looks ugly. I have an even worse problem with seq.
0-A + 1->B + 2->C + 3->C
I already experimented with adding literal seq to Alloy and got an experimental version running. Maybe sets could also be implemented this way:
// does not work in Alloy 4
seq [ A, B, C, C ] = 0->A + 1->B + 2->C + 3->C
set [ 1, 2, 3, 3 ] = 1+2+3
Today you could do this:
let x[a , b ] = { a + b }
run {
x[1,x[2,x[3,4]]] = 1+2+3+4
} for 4 int
But not sure I like this any better. If macros would have meta fields or would make the arguments available as a sequence (like most interpreters have) then we could do this
// does not work in Alloy 4
let list[ args ... ] = Int.args // args = seq univ
run {
range[ list[1,2,3,4,4] ] = 1+2+3+4
}
If you like the seq [ A, B, C, C ] syntax or the varargs then start a thread on the AlloyTools list. As said, I got the seq [ A, B, C, C ] working in a prototype.

Smalltalk / Squeak string shallow equality

The following code prints "false":
a := 'aaa'.
b := a deepCopy.
Transcript show: (a == b).
I do expect this behavior and my explanation to this would be that deepCopy returns a new object "b" that is a completely different object than "a" and since operator "==" compares by reference the result is "false". Is that correct?
However, I do not understand why the following code produces "true":
a := 'aaa'.
b := 'aaa'.
Transcript show: (a == b).
Here we made two assignments to two different objects, "a" and "b", and there shouldn't be any relation between them except the fact that they contain the same value. But if operator "==" compares by reference and not by value, why is the result of this comparison "true"?
The same misconception in both cases is that the question is not "what happens?", but "what is guaranteed?". The key is that there is no guarantee that 'aaa' == 'aaa', but the compiler and VM are free to do things that way. The same seems true for the case of copying; since strings are immutable, I guess there's nothing to say that copying a string couldn't return the same object!
In your first example, as usual, the best teacher is the image. #deepCopy delegates to #shallowCopy, which at some point evaluates class basicNew: index, and copies the characters into the new object. So, this particular implementation will always create a new object.
In addition to what Sean DeNigris said, the reason why the comparison is true in the second case is that when you execute all three statements together, the compiler wants to be smart and only once creates the object for 'aaa' and shares them for a and b.
The same happens if you put this into one method *:
Object subclass: #MyClassA
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'MyApp'
!MyClassA methodsFor: 'testing' stamp: nil prior: nil!
testStrings
| a b |
a := 'aaa'
b := 'aaa'
^ a == b
! !
MyClassA testStrings " ==> true"
But this does not happen if they are in different methods:
Object subclass: #MyClassB
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'MyApp'
!MyClassB methodsFor: 'testing' stamp: nil prior: nil!
a
| a |
a := 'aaa'
^ a
! !
!MyClassB methodsFor: 'testing' stamp: nil prior: nil!
b
| b |
b := 'aaa'
^ b
! !
!MyClassB methodsFor: 'testing' stamp: nil prior: nil!
testStrings
^ self a == self b
! !
MyClassB testStrings " ==> false"
That is because in Squeak, literal objects like stings are stored in the method object of the method they are defined in
*: Technically, every DoIt or PrintIt, that is when you just execute code by keystroke, gets compiled to one method in Squeak.
This is what I know from one of the free Smalltalk books scattered online but I can't find the reference:
As you would expect the instance of a class is a unique object in memory. deepCopy intentionally creates an object first and then stores a copy of the existing instance in it.
However numbers, characters and strings are treated as primitive data types by Smalltalk. When literal data, also referred to as literals, are assigned to variables they are first checked against a local scope dictionary which is invisible to the user and holds literals to check if they have been already added to it. If they haven't they will be added to the dictionary and the variable will point to the dictionary field. If identical literal data has been assigned before, the new variable will only point to the local scope dictionary field that contains the identical literal. This means that two or more variables assigned identical literals are pointing to the same dictionary field and therefore are identical objects. This is why the second comparison in your question is returning true.

Resources