r/ryelang • • Aug 30 '26

I made a match function (like switch)

I just started playing a bit with the language after just reading about it for a long time. It was nice to see how easy it was to get something working. And also cool to make my own control flow "primitive" (not primitive in this language), never done that before. I noticed that the switch function only checks the branches for equality with the input value, not pattern matching. So I made a "match" function. Still not pattern matching but at least it can check ranges. And other types of checks. Useful? I don't know... I just imagine that it could be.

match: fn { t branches } {
    forever {
        peek branches |^fix { t } ::branch , branches:: next branches
        peek branches |^check "Missing branch expression" ::expr , branches:: next branches
        
        if with t branch { return with t expr }
    }
}

porridge_temperature: 23

match porridge_temperature {
    { < 34 } { ++ " degrees is too cold." }
    { > 78 } { ++ " degrees is too hot." }
    { true } { ++ " degrees is just nice." }
} |print
3 Upvotes

2 comments sorted by

1

u/blackzver Aug 30 '26

*pattern matching. :)

1

u/middayc Aug 30 '26

Wow, interesting ... I wouldn't know how to approach writing this is Rye directly. I know how I would do it in Go ... I am not sure if I did right now. There is functions "cases" (that supports a little specific mechanism for multiple casres matching). REBOL has a case function that is very similar to your match.

This match-block is also different, but maybe a little related. https://www.reddit.com/r/ryelang/comments/1jgb364/new_matchblock_function/

All in all very interesting, thanks for sharing!