## Length

### June 29, 2018

Recently, at a beginning programmer’s forum, I saw a user asking about the function `length`

that finds the length of a list. He gave a simple version of `length`

, then used it find the lengths of two lists and determine which was shorter. He correctly realized that calculating the full lengths of both lists is inefficient if one list is much longer than the other, and he asked if there was a way to run through the lists simultaneously, stopping as soon as it is known which list is shorter.

Your task is to write `length`

and a function to determine which of two lists is shorter; your solution must use recursion. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

language like python tracks the length of list, so the get the length of list is constant time.

Here is a solution is standard Scheme that is easy to read as a

logical expression.

Here’s a solution in racket. The output is:

0 ==> The 1st list is shortest

1 ==> The 2nd list is shortest

2 ==> Both lists are of equal length

(define (shortest-list ls1 ls2)

(let check ((x ls1) (y ls2) (len 0))

(cond

((and (empty? x) (empty? y)) 2)

((empty? x) 0)

((empty? y) 1)

(else (check (cdr x) (cdr y) (add1 len))))))

@echo,

listsin Python are arrays, not linked-lists.https://docs.python.org/3/faq/design.html#how-are-lists-implemented

Here’s a solution in Common Lisp. The

shortestfunction returns 0 if both lists are the same size, 1 if the first list is shortest, and 2 if the second list is shortest.Example:

Here’s a solution in Haskell.

Example:

Klong version

shorter([]; [])

“Equal”

shorter([]; [1])

“1st”

shorter([1]; [])

“2nd”

shorter([1 2]; [3])

“2nd”

shorter([1 2]; [1 2 3])

“1st”

shorter([1]; [1])

“Equal”

Klong version (corrected)

ln::{ln2::{:[x~[]; y; .f(1_x; y+1)]}; ln2(x; 0)}

:monad

shorter::{:[0=ln(x)+ln(y); "Equal" :|ln(y)=0; "2nd" :| ln(x)=0; "First"; shorter(1_x; 1_y)]}

:dyad

Example:

Another Haskell solution, which is similar to Daniel’s. The main difference is that I’ve golfed it slightly to eliminate one case (at the expense of some symmetry in the arguments).

A good return type for the Haskell solutions re: length comparison is

`Ordering`

, which allows you to return LT, GT, or EQ values.A solution in Racket.

An answer in C#

@TomParish, it looks like your solution is simulating a linked list with an array.

Here’s a C# solution that uses a linked list directly. Unlike my earlier solutions, there is no attempt to make the length function tail recursive since this won’t be optimized in C#.

Output: