Lab 1: Functional Geometry
Bard College – Computer Science – Design of Programming Languages

In section 9.4 of “Programming in Lua,” Roberto Ierusalimschy develops a system for describing geometric regions using higher-order functions and closures. Earlier, Peter Henderson used similar ideas of functional transformations in his “Functional Geometry” paper (adapted into pict in SICP 2.2.4). In this week’s lab, we will combine these ideas (using scheme or lua).

# ​​Warming Up

Following Ierusalimschy, our first few functions describe shapes as predicate functions that take an (x,y) location and return whether that location is in the shape or not. For example,

​​function left(x,y) -- (number x number) -> boolean
​​  return x < 0
​​end

​​function unitc(x,y) -- (number x number) -> boolean
​​   return x^2 + y^2 < 1
​​end

Write a function blank that creates an empty blank image; and top that colors in the top half of the image.

​​plot(top, 400, 300, "top_test.pbm")

To actually see the image, we can write out a pbm file with desired width (M) and height (N).

​​function plot (r, M, N, filename)
​​   local file = io.open(filename, "w")
​​   file:write("P1\n", M, " ", N, "\n")
​​   for i = 1, N do
​​      local y = (N - i*2)/N
​​      for j = 1, M do
​​         local x = (M - j*2)/M
​​         file:write(r(x,y) and "1 " or "0 ")
​​      end
​​      file:write("\n")
​​   end
​​   file:close()
​​end

## ​​Constructing Predicates

Next, we can use higher-order functions to construct those kind of predicates.

​​function disk (cx, cy, r) -- (number x number x number) -> function
​​   return function (x, y) -- (number x number) -> boolean
​​      return (x - cx)^2 + (y - cy)^2 <= r^2
​​   end
​​end

describes a circle; and

​​function rect (left, right, bottom, up)
​​   return function (x, y)
​​      return left <= x and x <= right and bottom <= y and y <= up