Search code examples
schemegeneric-programming

Idiomatic scheme and generic programming, why only on numbers?


In Scheme, procedures like +, -, *, / works on different types of numbers, but we don't much see any other generic procedures.

For example, length works only on list so that vector-length and string-length are needed.

I guess it comes from the fact that the language doesn't really offer any mechanism for defining generic procedure (except cond of course) like "type classes" in Haskell or a standardized object system.

Is there an idiomatic scheme way to handle generic procedures that I'm not aware of ?


Solution

  • Finally, I found out a very neat solution in PLT Scheme :

    (require (rename-in scheme [length list-length]))
    
    (define length
     (λ (x)
      ((cond [(list? x) list-length]
             [(string? x) string-length]
             [(vector? x) vector-length]
             [else (error "whatever")]) x)))
    
    (length '(a b c))
    (length "abc")
    (length #(1 2 3))