Procedures


Procedures

A procedure is similar to a function. But instead of computing an answer, it just does a job. You use a function in an expression, but you use a procedure to make a statement.

In Cinnameg, a procedure has a name that begins with a capital letter. To define it, write the name of the procedure, then its argument(s), then a period, then an = sign. Follow the = sign by a sequence of statements that should be performed by this procedure. If you want to write types, add them directly to the arguments in the heading (just before the = sign). For example,

  Define
    WriteHelloTo(name: String). =
      Display "Hello, ".
      Display name.
      Display "\n".
  %Define
defines a procedure called WriteHelloTo that takes one argument, a name. It writes a greeting containing the given name. Notice the period just before the = sign. It is required.

Use a procedure in a way that is similar to how it appears in its definition, including the period. For example,

  Execute
    WriteHelloTo("Sam").
  %Execute
writes
Hello, Sam
on the console. Think of using a procedure as a sentence, and the period as the end of the sentence.


Procedures without any arguments

If your procedure has no arguments, just write an empty set of parentheses. For example, procedure SayHello defined by

  Define
    SayHello(). =
     Display "Hello\n".
  %Define
just displays Hello, followed by the end of the line. To use it as a statemtnt, write
  SayHello().


Problems

  1. [solve] Write a procedure PrintFortune(name), where name is a string. The procedure should write "You are wise" if the name begins with W, writes "You are intelligent" if name begins with R, and writes "You are generous" otherwise.

    Now write an Execute part that does PrintFortune with each of the names "Sam", "William" and "Robert".


Summary

A procedure just performs a job.

Use a capitalized name for a procedure.

When you define a procedure and when you use a procedure, write a period just after the procedure's arguments.

A statement looks like a sentence. It begins on a capitalized word and ends on a period.


Review

A command is called a statement.

A character is what you get when you type one key. Write a character in single quotes, such as 'Q'.

A string is a sequence of zero or more characters. Write a string in double quotes, such as "dragon".

There are several predefined operations for working on strings. Some of them are illustrated as follows.