cdiggins.com

April 30, 2007

Generalized Folds with Multiple Results

Filed under: Everything — cdiggins @ 9:59 pm

A fold is usually defined to take a list, an initial value, and a binary function. The function is applied to the first item in the list and the initial value, the result of which is combined with the first item in the rest of the list and so on. In Cat the type of the fold function is (list ‘a (’a ‘b -> ‘a) -> ‘a). 

For example in Cat we can compute the sum of a list of integers as follows:

define sum : (list -> int) { 0 [+] fold }

Stack-based languages have an interesting characteristic, functions can have multiple results. This means that we can generalize the fold so that instead of only accepting binary functions, it accepts any function taking n arguments and returning n - 1 results.

Let’s call the generalization “gfold” for fold, and give it the type: (’A list (’A ‘b -> ‘A) -> ‘A). Here is how you might use a gfold function to define a split function.

define split : (list (’a -> bool) -> list list)
{
  nil bury nil bury
  [dup] rcompose
  [[swap [cons] dip] [cons] if] compose
  gfold
}

The regular fold can be defined in terms of gfold as simply ”swapd gfold”.

Look for the gfold in the next release of Cat.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

Powered by WordPress