Logo

Programming-Idioms

  • Haskell
  • Scheme

Idiom #163 Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

(let print-pairs ((l list))
  (if (null? l)
      '()
      (begin
        (display (car l))
        (display " ")
        (display (cadr l))
        (newline)
        (print-pairs (cddr l)))))
pair :: [a] -> [(a, a)]
pair [] = []
pair (x:[]) = error "List had odd length"
pair (x:y:xs) = (x, y) : pair xs

mapM_ print (pair list)

Prints:
(a, b)
(c, d)
...
etc.
everySecond :: [a] -> [a]
everySecond [] = []
everySecond (_:[]) = []
everySecond (_:x:xs) = x : everySecond xs
everySecond' :: [a] -> [a]
everySecond' = everySecond . (undefined :)

mapM_ print (zip (everySecond list) (everySecond' list))
#include <stdio.h>
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);

I'm treating list as an array not a list because C doesn't have lists built in.
The length had better be even or there'll be undefined behaviour to pay!

New implementation...