Miscellaneous Functions


Here are a couple of miscellaneous functions that don’t really fit in anywhere. See if you can guess their intended functionality.

  1. (fun {flip f a b} {f b a})
  2. (fun {ghost & xs} {eval xs})
  3. (fun {comp f g x} {f (g x)})

The flip function takes a function f and two arguments a and b. It then applies f to a and b in the reversed order. This might be useful when we want a function to be partially evaluated. If we want to partially evaluate a function by only passing it in it’s second argument we can use flip to give us a new function that takes the first two arguments in reversed order.

This means if you want to apply the second argument of a function you can just apply the first argument to the flip of this function.

  1. lispy> (flip def) 1 {x}
  2. ()
  3. lispy> x
  4. 1
  5. lispy> def {define-one} ((flip def) 1)
  6. ()
  7. lispy> define-one {y}
  8. ()
  9. lispy> y
  10. 1
  11. lispy>

I couldn’t think of a use for the ghost function, but it seemed interesting. It simply takes in any number of arguments and evaluates them as if they were the expression itself. So it just sits at the front of an expression like a ghost, not interacting with or changing the behaviour of the program at all. If you can think of a use for it I’d love to hear.

  1. lispy> ghost + 2 2
  2. 4

The comp function is used to compose two functions. It takes as input f, g, and an argument to g. It then applies this argument to g and applies the result again to f. This can be used to compose two functions together into a new function that applies both of them in series. Like before, we can use this in combination with partial evaluation to build up complex functions from simpler ones.

For example we can compose two functions. One negates a number and another unpacks a list of numbers for multiplying together with *.

  1. lispy> (unpack *) {2 2}
  2. 4
  3. lispy> - ((unpack *) {2 2})
  4. -4
  5. lispy> comp - (unpack *)
  6. (\ {x} {f (g x)})
  7. lispy> def {mul-neg} (comp - (unpack *))
  8. ()
  9. lispy> mul-neg {2 8}
  10. -16
  11. lispy>