Try   HackMD

Pyret Crash Course for Java Programmers

This guide summarizes the essential notations that you'll need for the Pyret segment of the class. Keep in mind that Pyret is a full-fledged language and CSCI0200 will use only a small (yet powerful) portion of it. With the exception of looking in the documentation for the names of build-in functions on lists (and maybe strings), everything you need to know about Pyret will be covered in lecture.

If you are searching the documentation for some new construct or way to do things, you're almost certainly off-track! The point isn't for you to learn how to write the constructs you already know (like for-loops) in Pyret. The point is to get you to write similar programs to what you've written before with a different set of constructs. Lecture will cover those constructs.

Programs

In Java, you are used to thinking of everything in terms of classes. In functional programming, we often work with primitive data (numbers, strings, booleans) or with lists of primitive data. None of these need a notion of classes.

The simplest functional program is a single number, like

3

Yes, this is a complete program. Go to Pyret, type this at the prompt, and you get the value of this expression (which is, not surprisingly, 3).

Functions

Here is a function definition. Number is the type for all numbers (there is no distinction between integer, double, float, etc). doc is the documentation string. Functions live in your file, they don't have to be put inside anything (like a class).

fun square(n :: Number) -> Number:
  doc: "compute the square of a number"
  n * n
end

Note that there is no return annotation. In functional programming, function bodies consist of single expressions, or perhaps some statements naming intermediate values followed by the expression to compute. The result of that expression is the result of the function. Here's an example with intermediate value names.

fun big-square(n :: Number) -> Boolean:
  doc: "determine whether square of a number is above 100"
  sqr = n * n
  sqr > 100   # the result of this line gets returned
end

When you want to use a function, just call it with arguments, as you are used to doing in Java.

square(4)

Tests

CSCI0200 will put a lot of emphasis on writing tests. A collection of tests go into a check block. The two expressions on either side of the is are compared for structural equality.

check:
  square(6) is 36
  square(0.5) is 0.25
end

Lists

Lists are built in:

shopping = [list: "milk", "pie", "bread"]

Lists are actually objects in Pyret. You can write expressions over them using either function-notation or method-notation:

length(shopping)
shopping.length()  # note here that length is a method, not a field

You can get at elements of lists using first to get the first element and rest to get the list without the first element.

check:
 shopping.first is "milk"
 shopping.rest is [list: "pie", "bread"]]
 shopping.rest.first is "pie"
end

We don't have to write these list expressions in a check block, but we did so here to show you the result of using the list operators in a way that would run in Pyret.

Here is the Pyret documentation with the collection of built-in (functions and methods) on lists (down the left sidebar).

Functions as Arguments

One hallmark of functional programming is that functions can be passed as arguments and returned as the results of functions. Here's an example from the Pyret documentation that shows how to specify criteria for sorting a list:

a-list = [list: 'a', 'aa', 'aaa']
check:
  fun length-comparison(s1 :: String, s2 :: String) -> Boolean:
    string-length(s1) > string-length(s2)
  end
  fun length-equality(s1 :: String, s2 :: String) -> Boolean:
    string-length(s1) == string-length(s2)
  end
  a-list.sort-by(length-comparison, length-equality) is
    [list: 'aaa', 'aa', 'a']
end

Sometimes, when we pass a function as an argument, we don't want to bother naming it. Then, we can use a construct called lambda that defines a function but without giving it a name:

[list: "ab", "a", "", "c"].filter(lam(str): string-length(str) == 1 end)

Datatypes

A datatype describes the name and fields of a class (you are used to calling fields instance variables, but functional programming talks more in terms of structure of data and doesn't emphasize mutation).

Here are two examples: a cage is like a method-less class with two fields. boa and dillo are two kinds of Animal. Here, Animal is a type name, a role that interfaces can play in Java. boa and dillo name constructors that return values of type Animal. Pyret generates constructors and getters automatically from a data description.

data Cage: cage(width :: Number, height :: Number) end

data Animal:
  | boa(name :: String, length :: Number, eats :: String)
  | dillo(length :: Number, isDead :: Boolean)
end

# Examples of animals
veggie-boa = boa("slim", 24, "lettuce")
big-boa = boa("burk", 40, "cars")
dead-dillo = dillo(5, true)

Here's how to write a function over multiple variants of the same type. Cases is like a special/custom kind of if-statement that just serves to break down data types that have fields. Within the line for each constructor, the names in parens after the constructor (like nm, len, eats in boa) give local names to the field values within the value passed as ani.

fun fits-in(ani :: Animal, cg :: Cage): Boolean ->
  doc: "determine whether cage accomodates animal based on length" 
  cases (Animal) ani:
    | boa(nm, len, eats) => (len < (cg.width / 3))
    | dillo(len, isDead) => (len < cg.width)
  end
end

Often, we make lists of datatype values:

zoo = [list: dead-dillo, big-boa, veggie-boa]

Conditionals

Sometimes, you just need an if-else as part of the logic of your program:

temp = 50

if temp > 100: "hot"
else if temp > 75: "nice"
else: "too cold for me"
end

The value of the if-expression is the value of the answer for the first test that returns true.

Images

Pyret has some fun features that we won't use in 200, but that you could use to practice these early coding concepts if you'd like. Check out the images library.

above(
  star(50, "solid", "purple"), 
  rectangle(200,100, "outline", "green"))