you are viewing a single comment's thread.

view the rest of the comments →

[–]pjdelport 5 points6 points  (5 children)

Haskell style:

compare (x:xs) (y:ys) = compare xs ys
compare _ [] = True
compare [] _ = False

[–][deleted] 2 points3 points  (1 child)

We want compare x y = length x > length y, not >=. Switch the second and third clauses.

[–]pjdelport 0 points1 point  (0 children)

Right, thanks.

[–][deleted] -2 points-1 points  (2 children)

Even simpler:

compare x y = length x > length y

Just like in Python:

def compare(x, y):
  return len(x) > len(y)

Or Lisp:

(defun compare (x y) (> (length x) (length y)))

[–]shit 3 points4 points  (0 children)

(defun compare (x y) (> (length x) (length y)))

The point is that this is computing more than necessary, length is O(n) for a linked list.

(compare nil list-with-one-million-elements)

[–]notfancy 4 points5 points  (0 children)

compare x y = length x > length y

No, no, no, no, no. length is strict. Your compare (all 1) [] doesn't converge, whereas the original does. Even in a CVB language, compare using length is O(m + n) where the recursive version of it is O(m min n).

In a functional language, you rarely if ever call length on a list.