As I’ve worked in Haskell over the past several months, I’ve noticed that my mind has kind of implicitly modeled functional programming as a visual/mechanical representation of concepts. I’d like to make the ideas more explicit, however, so I’m writing this post and cooking up some graphics. I wonder if others have similar “internal representations” of functions, and if perhaps others might suggest improvements over my model.
The basic idea is that a function is a semi-circle with inputs on one side (left) and the output at the right. Colors represent types. Here is a function that takes one input and produces one output (of the same type):
Haskell would type this as “a -> a”. Next, we have a function that takes one type and returns a different type… e.g. a hashing function might take a string and return an integer:
(Please ignore the vertical stripe, it’s an artifact of my poor Inkscape skills). We can also create functions with more than one input, of course, so here is a binary function. It might be the ‘+’ operator, or some other binary operator, e.g. “a -> a -> a”:
Haskell and many other languages also have the concept of higher-order functions, i.e. functions that take functions as inputs. Here is a function that takes a binary function as input, along with another input, to produce an output of the same type:
There exist polymorphic types in many languages as well. In Haskell, for example, the list is a polymorphic type–it is a linked list of any type you want. I imagine these polymorphic types as “banded colors” so that the bands contain another type (color). Here is what the “head” function might look like (”head” returns the first element in a list):
Finally, here is a composite of all of the above visualizations. The “map” function in Haskell is a function that takes a function and a list, and applies that function to each element in the list, returning a new list with the “mapped” elements:
The type signature for the “map” function in Haskell is “(a -> b) -> [a] -> [b]“.
With these functions visualized, one could make a kind of “drag and drop” interface for Haskell programming, although that isn’t really my intention. I admit this is a little convoluted even for the purpose of visualization, but at least it’s a starting place. Does anyone know of another system or better representation?
Posted via email from Duane’s Quick Posts