zlacker

[parent] [thread] 3 comments
1. thauma+(OP)[view] [source] 2024-08-27 12:53:03
> It opens with a 'cond', with three branches. First branch is if the idx-th position in word is the same as letter, return green. Second branch is if the word includes the letter at all, yellow.

This is a tangent, but I've been thinking about how I feel when the conditions of an if-else ladder rely on the order they're listed in.

This is an example; if you swapped the order of those branches around, the coloration would become incorrect.

I'm a little happier when the conditions are described completely, such that swapping the order of the checks doesn't change which of them evaluate false or true, but it's also true that that can add quite a bit of complexity over an order-sensitive set of conditions.

Thoughts?

replies(3): >>Pet_An+Ch >>krferr+bi >>Zak+qI
2. Pet_An+Ch[view] [source] 2024-08-27 14:42:32
>>thauma+(OP)
I mean if the checks are expensive and it's on hot path, then that's wasteful.It might also require then to use more nesting of IFs which isn't necessarily nicer.
3. krferr+bi[view] [source] 2024-08-27 14:44:42
>>thauma+(OP)
Having the order matter and matching the first `true` branch makes for more readable and less-wordy if statements. Otherwise when you have two conditions which have any overlap, such as A and B, for the A branch you need to add `and not B` and for the B branch you need to add `and not A`. This can create very long expressions. Having them evaluate in order and only match the first true one makes this unnecessary.
4. Zak+qI[view] [source] 2024-08-27 16:52:49
>>thauma+(OP)
You could do something like this in Clojure:

    (first (filter identity
                   [(and (condition-three) (action-three))
                    (and (condition-one) (action-one))
                    (and (condition-four) (action-four))
                    (and (condition-two) (action-two))]))
And you could write a macro to do it with nice syntax. A bit more work and you could parallelize it.

You probably wouldn't want to most of the time, but if the conditions are slow to test but otherwise inexpensive, it might be a useful optimization.

[go to top]