Idiomatic scheme and general programming, why only by numbers?

In the schema, routines like +, -, *, / work with different types of numbers, but we don't see any other common routines.

For example, length only works in a list, so vector length and string length are needed.

My guess is that this is because the language does not really offer any mechanism for defining a general procedure (other than cond, of course), such as "class classes" in Haskell, or a standardized object system.

Is there an idiomatic outline of a way to handle common procedures that I am not aware of?

+2


a source to share


5 answers


Finally, I found a very neat solution in the PLT schema:



(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))  

      

+1


a source


Bearing in mind that all "different types of numbers" - all circuit numbers (ie (number? n)

equal #t

) - this behavior does make sense. +

, -

, *

, /

, And all other arithmetic operators work only with numbers (although in other languages they are classified as different types of numbers int

, long

, float

,, etc.). This is because you cannot explicitly declare number types in the schema.

If you really need a one-size-fits-all solution besides using external libraries, the easiest way is to make your own:



(define org-length length)
(define (length x)
  (cond
    ((string? x) (string-length x))
    ((vector? x) (vector-length x))
    ; keep going ...
    (else (org-length x))))

      

+2


a source


No, but you can create your own. Welcome to the Scheme!

I've used Swindle in the past to provide general functionality. It is associated with the PLT scheme . It worked for me, but several years have passed. There may be other alternatives.

+1


a source


Read the SICP sections 2.4 and 2.5, which cover the implementation of procedures that can work with generic data types by attaching "tags" to data objects. It's also in Lecture 4-B of this MIT video series.

+1


a source


You really want to have an object system for this. You might want to take a look at Tiny CLOS , which is the de facto standard object system for Chicken Scheme (see the reference manual ), but seems to be available for most Scheme implementations.

+1


a source







All Articles