Haskell for Perl ProgrammersBasic ExamplesLists

2.2. Lists

Reversing a List

myreverse
:: [a]
-> [a]

myreverse mylist
= helper mylist []
where
    helper
:: [a]
-> [a]
-> [a]

-- A stopping condition
    helper [] as
= as

-- Recurse
    helper (b
:bs) as
= helper bs (b
:as)

Run-Length Encoding

rle
:: Eq a
=> [a]
-> [(a,Integer)]

rle []
= []
rle (a
:[])
= [(a,
1)]
rle (x
:xs)
= (
if (x
== a)

then (a,count
+
1)
:as

else (x,
1)
:(a,count)
:as
             )
where
        ((a,count)
:as)
= (rle xs)

Quick-Sort

qsort []
= []
-- ++ is list concatenation
qsort (x
:xs)
= qsort elts_lt_x
++ [x]
++ qsort elts_greq_x

where

-- Choose the elements out of xs that are lesser than x
                   elts_lt_x
= [y
| y
<- xs, y
< x]
                   elts_greq_x
= [y
| y
<- xs, y
>= x]

Written by Shlomi Fish