Structures provide a means of grouping related data into an entity. Most modern languages contain a context similar to structures. Languages such as C and C++ also support structures where as languages like Java and C# support classes. Note: structures are not classes. Classes are much more flexible as they support features such as information hiding, inheritance and allow you to define your own methods. Structures do not have these features.
Structures are useful for implementing data structures in Scheme.
Built-in Scheme Structures – Posn
Posn is a built-in Scheme structure that has two fields x and y. In other words, this structure is meant to represent a point on a Cartesian grid.
We create a posn like this:
(make-posn 3 2)
This is the constructor function which takes 2 parameters x followed by y. So in this case the x coordinate is 3 and the y-coordinate is 2.
It is important at this point to mention that Scheme is not a strongly typed language. It is syntactically valid to write:
(make-posn 'Hi 'CodeCall’)
But in a logistic sense this doesn’t make any sense. You may recall that a posn represents a point on a grid. (‘Hi, ‘CodeCall) doesn’t represent any point on a Cartesian grid. This is why when we write structures and functions we write a contract that the programmer must adhere to. If the contract is broken then bad things can happen. We want to write our programs so that if the contract is adhered to then the program will function properly.
We can write checks to ensure that types passed to our function are valid if we want. We will see how to do this in a later tutorial.
Now let us look at selectors.
When a structure is created a selector function is created for every field. The selector function takes the form: (structname-fieldname struct)
So in the posn example if we want the x-value we can do the follow:
(posn-x posn) ;; returns the x value of the posn (posn-y posn) ;; returns the y value of the posn
(posn-x (make-posn 3 2))
This code produces the x value of the posn which in this case is 3. If we did (posn-y (make-posn 3 2)) the value produced would be 2.
Another function created when we create a structure is a predicate function named struct-name? which returns true if a value is that particular structure. As we will see later this is useful when dealing with recursive structures.
(posn? 5) ;; false (posn? (make-posn 3 2));; true
Next time we look at creating our own structures! Any questions, post below!
Edited by chili5, 21 August 2011 - 06:11 AM.
added selector examples and table of contents