Search code examples
smalltalksqueak

Squeak Smalltalk- How to make to "Transcript show" print more things?


I am using Smalltalk to type in Transcript window a 1-9 multiplication table .

Here is my code:

1 to: 9 do: [:i|
    1 to: i do: [:j|
        Transcript show: j.
        Transcript show: ' * '.
        Transcript show: i.
        Transcript show: ' = '.
        Transcript show: j * i.
        Transcript show: '  '.
        ].
    Transcript show: ' '; cr.
    ].

As can be seen, the above code, although working fine, looks far from beautiful and concise.

I had hoped to write something like :

Transcript show: j '*' i '=' j * i.

Unfortunately, they are wrong. I remember C has a very nice way to handle that issue of mine.

Like, printf("%d * %d = %d ", j, i, j * i);

Is there a more elegant way to make Smalltalk codes elegant in this situation ?


Peter solves this problem. Thanks.

More to ask:

How to display "Escape character" in Smalltalk.

I know in C, printf("%d * %d = %d\n", j, i, j * i); seems fine.

But in Smalltalk, Transcript show: ('{1} * {2} = {3}cr.' format: {i. j. i * j}). is not OKAY.

How can I solve that?


Solution

  • String expansion

    Like, printf("%d * %d = %d ", j, i, j * i);

    There are some options for formatting, but nothing comparable to printf (afaik)

    '<1p> * <2p> = <3p>' expandMacrosWith: 2 with: 3 with: 2 * 3.
    "same as the following:"
    '<1p> * <2p> = <3p>' expandMacrosWithArguments: {2. 3. 2 * 3}.
    
    '{1} * {2} = {3}' format: {2. 3. 2 * 3}.
    

    So your code could be rewritten as the following

    1 to: 9 do: [ :i |
        1 to: i do: [ :j |
            Transcript
                show: ('{1} * {2} = {3}' format: {j. i. j * i});
                show: ' '
        ].
        Transcript show: ' '; cr.
    ].
    

    Update re: escape characters

    There are no escape characters in Strings with the only exception being single quote ('), which you "escape" by doubling it ('It''s doubled!')

    To write new line, or tabulator, you can

    1. type it into the string

      a := 'two lines'. (note that StackOverflow replaced the tab with spaces :/)

    2. Join strings

      b := 'two', String cr, String tab, 'lines'.

    3. Tell write stream to add it

      c := String streamContents: [ :stream | stream << 'two'; cr; tab; << 'lines' ].

    4. use expandMacros

      d := 'two<n><t>lines' expandMacros.

    a = b = c = d