Haskell for Perl ProgrammersList and String Manipulation RoutinesExamples

4.1. Examples

Greatest Common Prefix of a List of Strings

prefix_2
:: Eq a
=> [a]
-> [a]
-> [a]

prefix_2 xs []
= []
prefix_2 [] xs
= []
prefix_2 (a
:as) (b
:bs)
=
if a
== b

then a
:(prefix_2 as bs)

else []

-- Can also be expressed as:
prefix_2_other xs ys
= map fst
. takeWhile (uncurry (
==))
$ (zip xs ys)

gc_prefix
:: Eq a
=> [[a]]
-> [a]

gc_prefix []
= []
gc_prefix (a
:as)
= foldl prefix_2 a as

Split

import List

mysplit
:: Eq a
=> [a]
-> [a]
-> [[a]]

mysplit separator base
= helper base
where
    len
= (length separator)
    helper []
= [[]]
    helper base
=
        (
if (isPrefixOf separator base)

then []
:(helper (drop len base))

else
let ret
= (helper (tail base))

in (head(base)
:head(ret))
: tail(ret)
        )

Written by Shlomi Fish