Caterpillar

Daily Thought - 2024-08-13

< back to list

To replace if, I've implemented pattern matching in function definitions. What does that mean? Well, pattern matching is a feature in many programming languages that allows you to look at a value, and then decide what to do, based on what the value is. Here's a basic example in Rust:

let message = match n {
    0 => "We have nothing!",
    1 => "We have one!",
    _ => "We have many!",
};

This is just a simple example to demonstrate the concept. More advanced matching is possible, but I won't go into that right now.

There's a neat thing that some functional languages support: Pattern matching in function definitions. Here's the same example using that technique (in a fictional pseudo-code, because Caterpillar still has no syntax, nor strings):

fn 0 to_message:
    "We have nothing!"

fn 1 to_message:
    "We have one!"

fn _ to_message:
    "We have many!"

Here, instead of doing pattern matching within a function, we create three functions, each called to_message, that have a pattern in their parameter lists. The pattern matching happens when we call the functions; then the right one is selected based on the argument. So the call 0 to_message would call the first function, 1 to_message would call the second.

<< previous thoughtnext thought >>