idiom


An idiom is from latin, idioma meaning individual peculiarity of language. In the world of programming languages, However, it is often taken as term for a common structure, method or style used by a large subgroup of the people programming the particular language.

Learning the idioms will make you able to comprehend others code faster, and it also enables you to write code which is easier understood by a large group of programmers.

A common idiom in Scheme, for instance, is to avoid imperative programming based on the fact that imperative functions are harder to debug, prone to errors, harder to comprehend and needs a greater spatial understanding of the code (there is no locality).

On another level, a common idiom of scheme code is to traverse a list. For instance the sum function could be written as:

 (define (sum lst) 
   (if (null? lst) 
       0 
       (+ (car lst) (sum (cdr lst))))) 

It is not tail-recursive, but this is not the point of the following. Let us also take a function to compute the length of a list:

 (define (length lst) 
   (if (null? lst) 
       0 
       (+ 1 (length (cdr lst))))) 

These 2 functions share a common idiom. Namely the fact that we have a base-case when the list satisfies the null? predicate and a recursion-case where we take the car of the list, and the recursive call on the cdr of the list and combines them with some function (in this case (+ ...)).

We can catch this common idiom in the following definition

 (define (list-recurser rec base) 
   (define (self lst) 
     (if (null? lst) 
         (if (procedure? base) 
             (base) 
             base) 
         (rec (car lst) (lambda () 
                          (self (cdr lst)))))) 
   self) 

And then we can easily define our 2 functions from before as:

 (define sum2 (list-recurser (lambda (x f) (+ x (f))) 0)) 
 (define length2 (list-recurser (lambda (x f) (+ 1 (f))) 0)) 

Which is more concise and far easier to write, performance aside.