Writing a generic max function

8 views
Skip to first unread message

Bill Cox

unread,
May 9, 2023, 2:26:07 AM5/9/23
to Rune language discussion
Rune's polymorphism is primarily based on Python-like function definitions that do not needlessly restrict polymorphism.  Consider the basic "max" function.  Rune has this in builtin/misc.rn

// Return the max of |a| and |b|.  Safe to use with secrets.
func max(a, b) {
  return a >= b? a : b
}

Who would have trouble writing this in under a minute?  The ?: operator being constant-time for secrets is a nice bonus.  Here's the Rust version:
pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
    match compare(&v1, &v2) {
        Ordering::Less | Ordering::Equal => v2,
        Ordering::Greater => v1,
    }
}
Who could write this in 5 minutes?  Traits as a vehicle for polymorphism are, IMO, a failed experiment.

Bill

Aiden Hall

unread,
May 9, 2023, 10:03:08 AM5/9/23
to Bill Cox, Rune language discussion
IMO the only reasonable polymorphism I have seen is the system of implicit inlining that Go uses.

--
You received this message because you are subscribed to the Google Groups "Rune language discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rune-discuss...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rune-discuss/CAH9QtQESFcy%3DoPnbxptatjEoTsahA_47Sjj5RTa3HcMUx%3DQU6w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Andrew Wilson

unread,
May 9, 2023, 11:54:24 AM5/9/23
to Aiden Hall, Bill Cox, Rune language discussion
max is an interesting example because it only works if the type supports a total ordering, so it's not "completely polymorphic" in the sense that, say, reversing a list, can be.

You need the notion of a type hierarchy or type class, subtypes, e.g., 'int' is a subclass of 'totally ordered type".

For a functional programming example, (say, Standard ML)  we can write fun max(a, b) = if a < b then b else a;  and that looks polymorphic, but in fact, if declared at the top-level, SML will give it the int type, because "<" is not polymorphic, it is a built-in 'overloaded' operator.  *However*, if the surrounding context of the definition showed that a, b or both would be a string type, then it would be typed string * string -> bool.

The interesting question here for Rune is - what is the type of  '>='?  does Rune support type classes?

Cheers
Andrew


For more options, visit https://groups.google.com/d/optout.


--
Andrew Wilson
Software Engineer, Android TV Eng Prod
Reply all
Reply to author
Forward
0 new messages