Reactors and Posns

Reactors

my-reactor =
reactor:
    init: init-posn,
    to-draw: crime-scene,
    on-tick: solve-case,
    on-key: move-glass,
    stop-when: found-it
end

Posns and Datatypes

data Posn: 
    | posn(x :: Number, y :: Number)
end 

What is a datatype? You’re already familiar with a few… int and string are examples of datatypes you’ve already used! But what if the kind of data that you’re working with in your program is not well-described by a type that Pyret has built-in for you? Let’s say that you’re building a house. Every function that helps to build the house (maybe build-foundation, lay-bricks, shingle-roof) has to know the x- and y-locations where you’d like to build something. Instead of passing the x- and y-values as separate inputs to each of these functions, you can store both locations together in a new datatype (calling it Position, or Posn for short)! Much like the way a variable of type int “knows” its value, a Posn also knows its value. BUT in this case, the value just happens to have two separate pieces of information, the x- and y-location. In this way, we see that we can simplify and module our code to use and store data effectively.

By defining a posn datatype, you are telling the program, “This is something that will appear later in my program, and I want a way to build the same thing multiple times with different characteristics.” So, when you make a posn in your program, you are building the same structure each time: a variable of type posn! The difference between the posn variables you make are the x, y values entered as parameters (inputs).

A slightly more complicated example

Let’s say you want to build a new data type that represents an animal. What kind of information do you need to know about an animal? Maybe how much it weighs, if it has hair and what color it is?

Here is how we would declare an animal data type:

data Animal:
  | animal(has-hair :: Boolean, weight :: Number, color :: String)
end

To create an Animal, we would write:

poodle = animal(true, 20, "black")

And to find out if this poodle we just created has hair, we can write poodle.has-hair and the result of this line of code will be the Boolean true because our poodle, as we defined it, has hair!

Confused? Ask a TA! This is a challenging concept, and it may take a little while for this idea to sink in. Don’t worry if it doesn’t make sense yet, it will with time and practice!