[Haskell-cafe] class Defaults

Bulat Ziganshin bulat.ziganshin at gmail.com
Wed Nov 1 14:26:45 EST 2006


Hello haskell-cafe,

just one more nice snippet of code:

class    Defaults a      where defaultValue :: a
instance Defaults Bool   where defaultValue = False
instance Defaults [a]    where defaultValue = []
instance Defaults (a->a) where defaultValue = id
instance Num a => Defaults a where defaultValue = 0

class    TestDefaultValue a    where isDefaultValue :: a -> Bool
instance TestDefaultValue Bool where isDefaultValue = not
instance TestDefaultValue [a]  where isDefaultValue = null
instance Num a => TestDefaultValue a where isDefaultValue = (==0)

-- This function is useful for defining default values,
-- such as (directory ||| ".") or (memsize ||| 10*mb)
a ||| b | isDefaultValue a = b
        | otherwise        = a

-- Useful for short-cutting boolean expressions, like this:
--   putStr$ (need_separator &&& "\n\n") ++ (need_attention &&& map toUpper) str
a &&& b | isDefaultValue a = defaultValue
        | otherwise        = b

-- |Apply function to value only if it is not empty
unlessNull f xs  =  xs &&& f xs

-- |Recursive list processing until list end,
-- for example 'recursive (splitAt n)' splits list
-- into the chuunks of n elements
recursive :: ([a]->(b,[a])) -> [a] -> [b]
recursive f list  =  list &&& (x:recursive f xs)   where (x,xs) = f list

-- |Split list into parts whose size defined by calling len_f
-- at the yet unprocessed parts of list
splitByLen :: ([a]->Int) -> [a] -> [[a]]
splitByLen len_f  =  recursive (\xs -> splitAt (len_f xs) xs)


-- 
Best regards,
 Bulat                          mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list