Simple Input and Output Example

No introduction to a programming language is complete without giving the opportunity for the computer to shout "Hello World" for the universe to see. In occam on the transputer and through KRoC, the screen is available as a special byte output channel. As a byte channel, characters must be written one at a time, as in the following example:

    PROC hello.world (CHAN OF BYTE keyboard, screen, error)
      SEQ
        screen ! 'H'
        screen ! 'e'
        screen ! 'l'
        screen ! 'l'
        screen ! 'o'
        screen ! ' '
        screen ! 'W'
        screen ! 'o'
        screen ! 'r'
        screen ! 'l'
        screen ! 'd'
        screen ! '*c'
        screen ! '*n'
    :                                                               
    


Writing output one byte at a time is particularly tedious, so libraries containing procedures with common higher-level functionality are available. The KRoC package includes several libraries including one which manipulates strings for output. An excerpt from the library, written completely in occam, appears below. Here, the procedure out.string writes a right-aligned string of length "field" to the specified output channel. It uses the procedure out.repeat to insert spaces to pad the field as necessary.

    -- Segments from library utils.occ
    -- Peter Welch, 1997
    
    PROC out.string (VAL []BYTE s, VAL INT field, CHAN OF BYTE out) 
      --This outputs `s' in a fieldwidth `field' down `out'.
      VAL INT length IS SIZE s:
      SEQ
        out.repeat (' ', field - length, out)
        SEQ i = 0 FOR length
          out ! s[i]
    :
    
    PROC out.repeat (VAL BYTE ch, VAL INT n, CHAN OF BYTE out)
      --This outputs `ch' down the channel `out' `n' times.
      IF
        n > 0
          SEQ i = 0 FOR n
            out ! ch
        TRUE
          SKIP
    :                                                             
    


Using the library routine, writing a string to output is very easy:

    -- HelloWorld.occ
    -- Peter Welch, 1997
    USE "course.lib"
    PROC hello.world (CHAN OF BYTE keyboard, screen, error)
      out.string ("Hello World*c*n", 0, screen)
    :                                                               
    


Next: Parallel sorting example
Return to Index