I’m learning smalltalk right now and am trying to make a very simple program that creates an array of numbers and then finds the largest number. My code looks like this:
| list max |
list := #(1 8 4 5 3).
1 to: list size do: [:i |
max < (list at: i)
ifTrue: [max := (list at: i)].
ifFalse: [max := max].
].
When I run this code, I get “stdin:7: parse error, expected ‘]'”. I’m a bit confused as to what is causing this. It looks to me like all of my square brackets correspond. Help?
Your immediate problem is that you terminate the
ifTruesection with a period. You could normally just remove the period but, since yourifFalsesection is effectively a non-operation, it’s probably better to remove that bit.But even when you fix that, you still need to initialise
maxso that you don’t get a<message being sent to thenilobject. You can initialise it to the first element, if there are any, then you can change the loop to start at the second.Of course, initialising to the first element is problematic when the list is empty so you should handle that as well. In the code below, I’ve set it to a suitable small value then initialised it from the first element of the list only if it’s available.
Corrected code is:
This outputs
8as expected and also works fine on the edge cases (list size of zero and one).