Learn to Program using Alice

Functions that Return Values

Learn about functions that return values in Alice.  Learn how to use existing functions, as well as how to write your own new functions.

Last updated:  August 26, 2007
By Richard G. Baldwin

Alice Programming Notes # 135


Preface

Part of a series

This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.

Have some fun

Because Alice is an interactive graphic 3D programming environment, it is not only useful for learning how to program, Alice makes learning to program fun.  Therefore, you should be sure to explore the many possibilities for being creative provided by Alice while you are learning to program using these tutorials.  And above all, have fun in the process of learning.

General

In the previous lesson titled "Learn to Program using Alice, The Program Development Cycle" (see Resources), I walked you step-by-step through the design, specification, coding, testing, and debugging of a complete Alice animation program.

The program design was presented in the form of a two-act play.  It was subdivided into two acts and several scenes, with some special effects used to emphasize the transitions between scenes.

The emphasis in that lesson was on the design and organization of a computer program.  The actual code that implemented the program included some important programming concepts that I hadn't previously covered in this series of tutorials.  In some of those cases, I deferred the explanation of the code to future lessons that will concentrate on those concepts.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

Listings

Supplementary material

Once you have mastered Alice, I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

You learned how to subdivide your program into programming modules in the earlier lesson titled "Learn to Program using Alice, The Program Development Cycle" (see Resources).

Subroutine modules in FORTRAN
According to Wikipedia "IBM's FORTRAN II appeared in 1958. The main enhancement was to support procedural programming by allowing user-written subroutines and functions."

FORTRAN subroutines

The capability to subdivide a program into separate programming modules has been around since before I first learned how to program using the FORTRAN programming language in early 1962.

Can I avoid calling functions by the wrong name?
During the past eleven years, I have written hundreds of Java programming tutorials.  Thus, the name method is emblazoned in my brain.  I will be amazed if I make it through the writing of this entire lesson without inadvertently calling a function by the name method.

A function by any other name...

Over the years, and through various computer programming languages, the names by which the programming modules are identified have changed.  For example, with the advent of C and C++, they were called functions.  With the advent of Java (and possibly before), they were called methods.  Many authors writing about C# seem to arbitrarily switch back and forth between the name function and the name method.  In most cases, it doesn't matter a lot what you call them as long as you know what they are.  However, it does matter in Alice because Alice has both methods and functions.

Methods and functions

Alice has both methods and functions.  The distinction seems to be:

This lesson will deal primarily with functions and the values that they return.

What does it mean to return a value?

One way to describe the returning of a value by a function is to say that if a call to a function is contained in an expression in a statement, when control return from the function, that call to the function will effectively have been replaced by the returned value.

Primitive functions and programmer-defined functions

All objects in Alice, including the world, the camera, the light, the ground, and objects created from the classes in the gallery provide a variety of functions in addition to a variety of methods.  These functions are what I will refer to as primitive functions.

In addition, you can create a new function and attach it to any of the Alice objects.

We will investigate both the use of primitive functions and the creation and use of programmer-defined functions in this lesson.

Preview

In this lesson, I will teach you about functions that return values in Alice.  I will teach you how to use existing functions, as well as how to write your own new functions.

Discussion and sample code

The program named Alice0135a

This program demonstrates the use of several primitive functions.  A complete listing of this program is provided in Listing 1 near the end of this lesson.  In addition, you can download an Alice a2w file containing an executable copy of this program (see Resources).

Behavior of the program

The method named say is called on the coach object with outstretched arms for the purpose of displaying the coach's current width as shown in Figure 1. 

Several functions belonging to both the coach and the world are called to get and format the width information and to display it on the computer screen as shown in Figure 1.

Figure 1. Coach with outstretched arms in program named Alice0135a.

Raise your arms and do it again

Then the coach is asked to raise both arms, and to report his new width as shown in Figure 2.

Figure 2. Coach with arms raised high in program named Alice0135a.

Explanation of the program code

To write and run this program, create a new world, add a coach to the world, and save it in a file named Alice0135a.

In order to help you better understand the procedure for constructing a fairly complicated call to the say method on the coach object, I included four sequential calls to the say method in the code block identified by the comment that reads "Show various stages of construction of statement" in Listing 1. 

Three intermediate screens

When you run the program, you will see three intermediate screens before you see the screen that is shown in Figure 1.  For example, the first screen that you will see is shown in Figure 3.  On the strength of what you have learned in earlier lessons in this series, you should recognize Figure 3 as the result of calling the say method on the coach object for the first time in the block of code identified above.

Figure 3. First intermediate screen in the program named Alice0135a.

Types Number and String

Alice is a so-called "type sensitive" programming language, which requires different kinds of data to be categorized in different ways, technically known as data types.  I plan to get into data types in some detail in a future lesson, so I don't want to get too involved in that topic in this lesson.  However, we do need to distinguish between two types:  Number and String.

The best way that I know how to describe the Number type is that you can do arithmetic with a value of type Number.

The String type might best be described as a series of characters that are used to create something that in the non-technical world might be called a label.  For example, you would probably use type String to describe your name and perhaps your telephone number.  However, if you were to describe your telephone number as type String, you would not be able to do arithmetic with it, even if it consisted solely of the characters ranging from 0 through 9 inclusive.  You can only do arithmetic with values of type Number.

The say method and type Number

The say method requires a single parameter, and it must be type String.  The parameter of type String that is passed to the say method is what gets displayed in the comic-strip bubble in Figure 3.  The say method won't accept an incoming parameter of type Number.  Therefore, we must find a way to convert the coach's width value from type Number to type String in order to be able to pass it to the say method for display.

The world's toString function

Fortunately, the world provides a function named toString that can be used for this purpose.  When data of type Number is involved, the use of this function is a little more complex than simply passing a parameter to a function as you will see in the paragraphs that follow.

Concatenating strings

The say method accepts only a single String as an input parameter and displays it on the computer screen as shown in Figure 3.  However, once we convert the numeric value that constitutes the coach's width to a String, we have two different strings that we want to be displayed together as shown in Figure 1.  Those two strings are:

Therefore, we must find a way of fusing those two strings into a single String that we can pass to the say method for display.

The process of fusing two or more strings into a single String in computer programming jargon is concatenating stringsFortunately again, the world provides a function named a+b that can be used for this purpose.

Method and function calls

In order to get and display the width of the coach object as shown in Figure 1, we must call the following methods and functions in the order shown below:

The sequential calls to these methods and functions are illustrated in the block of code identified above in Listing 1.

The ultimate goal in that block of code is to write the last statement in the block of code, which is a call to the coach's say method with the single String parameter having been constructed by embedded calls to the functions listed above.  (This code could have been simplified somewhat through the use of local variables, but we haven't studied that topic yet.)

The drag and drop paradigm gets in the way

This is a case where Alice's drag and drop programming paradigm tends to get into the way.  If this were a typical programming language where you simply type in the code, all I would need to tell you in order to explain how to write the code would be to tell you to copy the last statement in the block.  I would then need to explain how the different parts of the statement behave.  The order in which you typed the characters to create the statement wouldn't matter as long as you got the statement typed correctly in the end.

However, with the drag and drop paradigm, you must construct the statement by dragging in the component parts of the statement in a very specific order, and creating placeholders a couple of times along the way.  This makes it much more difficult to explain.  That is why I am showing you four different versions of the call to the say method in Listing 1.  Hopefully, you can analyze the comments and the differences between the statements and can understand what is required to construct the statement in terms of drag and drop procedures.

I invite you to replicate the code in Listing 1, run the program, and observe the results.  Then experiment with the code, making changes and observing the results of those changes.

The program named Alice0135b

In this program, I will show you how to write a function that returns a value.  In particular, the world that I will use in this program contains a coach and a chicken as shown in Figure 4.  We will write a new function for the coach object that make it possible for code in the main method to send a message to the coach asking it how far it is from the chicken.  The coach object will get and return that value, which will be printed by the main method in the large white space at the bottom of the World Running screen as shown in Figure 4.

Figure 4. The coach and the chicken in program named Alice0135b.

Create a new world and define a function

Begin by creating a new world containing a coach and a chicken as shown in Figure 4.  Then select coach in the object tree, and open the functions tab below the object tree.  Click the button labeled create new function in the functions tab.  This will produce a dialog similar to that shown in Figure 5.

Figure 5. Function creation dialog in program named Alice0135b.

Define the skeleton of the new function

Enter the name of the new function in the text field at the top of the dialog and click the Number button to specify that the function will return a value of type Number.  Leave everything else as it is in Figure 5 and click the OK button.

A new edit tab

This will create a new tab in the edit pane.  A partial screen shot of the new tab is shown in Figure 6.

Figure 6. Function edit tab in program named Alice0135b.

As you can see, the name of the new function is shown in the top of the tab.  Immediately below that is the signature for the new function.

The body of the function

Although you can't see it in Figure 6, there is a curly brace at the bottom of the edit pane that matches the one at the end of the function signature.  Everything between that pair of matching curly braces constitutes the body of the function.  Initially, that body is empty except for a return statement that will, by default, return the value 1.

Correct the return statement

We don't want this function to return the value 1 when it is called.  Rather, we want it to return a value that is the distance between the center of the coach and the center of the chicken.

One of the functions that is provided by the coach object can be called to provide that information.  Open the functions tab for the coach object.  Drag the function named distanceTo from the functions tab and drop it on top of the 1 that is showing as the return value in Figure 6.  This should result in source code for the function named getDistanceToChicken that matches the source code for that function in Listing 2.

That's all there is to it

Admittedly, the body of this function is very simple.  However, now you know how to define a new function for an object regardless of how simple or how complex the body of the function may be.  Just follow the steps outlined above and fill in the code in the body of the function to cause it to behave the way you want it to behave and to return the value that you want it to return.

Calling the getDistanceToChicken function

The code in the main method in Listing 2 calls the getDistanceToChicken function on the coach and prints the results.  As was the case in the earlier program in this lesson, it is necessary to convert the numeric result returned from the function to type String and to concatenate it to the other text in the printed output.  The procedure used to accomplish this is the same in both programs.

Memorize this procedure

When programming in Alice, you will frequently need to convert numeric values to type String for various purposes.  I recommend that you memorize this procedure so that you will have it handy in your brain whenever you need it.

The final output

The output produced by the print statement in the main method is shown in the white area at the bottom of Figure 4.

Run the program

Both programs that I explained in this lesson are available for downloading (see Resources).  I encourage you to either download those programs, or copy the code from Listing 1 and Listing 2 into your Alice development environment and play it.  Experiment with it, making changes, and observing the results of your changes.

Summary

In this lesson, I taught you about functions that return values in Alice.  I taught you how to use existing functions.  I also taught you how to write your own new functions.

Lab project

Begin with the program named Alice0135b above.

Create and add a new function belonging to the Coach object named getChicken.

Update the main method to that shown in Listing 3.

Listing 3. Updated main method for Alice135LabProjA.a2w.
  public void main ( ) {
    
       // Copyright 2007 R.G.Baldwin
  // Program demonstrates defining two new functions.
  doInOrder {
       print( ( Distance to chicken is: + ( ( coach.getDistanceToChicken ( ) ) .toString() ) ) );
  ( coach.getChicken ( ) ) .turn( RIGHT , 2 revolutions );
  }
  }

When you play your world, it will display the distance from the coach to the chicken as shown in Figure 4 (it is not necessary to match the value of the distance shown in Figure 4).  Then the chicken will turn to the right, making two complete revolutions around its own green axis.

Save your world in a file named Alice135LabProjA.a2w and be prepared to deliver it to your instructor in whatever manner the instructor specifies.

Make certain that your preferences are set to Java Style in Color.

Select Export Code For Printing... on the File menu and save your source code in a file named Alice135LabProjA.html.  Also be prepared to deliver this file to your instructor in whatever manner the instructor specifies.

View a movie of the lab project

You can download and play a small, low-quality movie of my version of the lab project as it being executed from the Resume button (see Resources).  This movie was designed to give you a rough idea of how your program should behave.  The movie was purposely recorded in low-quality wmv format in a small window in order to reduce the file size and hence reduce the download time.

Note that each time you click the Restart button, a new line of output text is displayed.  That is the reason that several lines of output text appear in the movie.  The world was played several times before capturing it into the movie.

Because of the low quality of the movie, the execution of your program should provide much smoother animation than the movie, and should be much less grainy than the movie.  Also, because of the low quality of the movie, the timing in the movie doesn't necessarily match the duration times specified for the lab project.

I attempted to synchronize the beginning of the recording with the beginning of the program execution by starting, then quickly pausing, and then resuming the execution.  If you watch closely, when the movie starts running, you will see the mouse pointer click the Resume button, and the movie will show one complete pass through the program.

You should view this movie in its original size.  If you allow the media player to enlarge it, the quality will be poor.

What's next?

In the next lesson, I will teach you about data types and variables.  As mentioned earlier, in some cases, variables can be used to simplify the construction of Alice statements such as the calls to the say method in Listing 1.  Variables also have other purposes as well.

Resources

Complete program listings

Complete listings of the programs discussed in this lesson are shown in Listing 1 and Listing 2 below.

Listing 1. Source code for the program named Alice0135a.

Alice0135a's Code

Created by: Dick Baldwin

world

Methods

  public void main ( ) {
    
       // Copyright 2007 R.G.Baldwin
  // Program demonstrates the use of value-returning functions.
  doInOrder {
       // Coach reports his current width.
  // Show various stages of construction of statement.
  doInOrder {
       // Begin constructing the statement.
  coach .say( My width is );
  // Drag in world's (a+b) function.
  coach .say( ( My width is + dummy ) );
  // Drag in world's what.toString() function.
  coach .say( ( My width is + ( coach .toString() ) ) );
  // Drag in coach.getWidth() function.
  // and set duration property.
  coach .say( ( My width is + ( ( subject = coach .getWidth() ) .toString() ) ) ); duration = 5 seconds
  }
  }
  // Coach raises both arms and reports new width.
  doInOrder { . . }
       doTogether {
       coach.upperBody.leftArm .roll( RIGHT , 0.25 revolutions );
  coach.upperBody.rightArm .roll( LEFT , 0.25 revolutions );
  }
  coach .say( ( Now my width is + ( ( subject = coach .getWidth() ) .toString() ) ) ); duration = 5 seconds
  }
  }

 

Listing 2. Source code for the program named Alice0135b.

Alice0135b's Code

Created by: Dick Baldwin

world

Methods

  public void main ( ) {
    
       // Copyright 2007 R.G.Baldwin
  // Program demonstrates defining a new function.
  doInOrder {
       print( ( Distance to chicken is: + ( ( coach.getDistanceToChicken ( ) ) .toString() ) ) );
  }
  }


coach

Functions

  java.lang.Number public Number getDistanceToChicken ( ) {
    
       // Get and return the distance to the chicken.
         return ( coach .distanceTo( Chicken ) ) ;
  }

 


Copyright

Copyright 2007, Richard G. Baldwin.  Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process.  This license does not extend to commercial ventures.  Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-