[Haskell-cafe] Filter by several predicates at once

Bulat Ziganshin bulat.ziganshin at gmail.com
Thu Jan 17 13:00:55 EST 2008

Hello Isaac,

Thursday, January 17, 2008, 5:46:20 PM, you wrote:

> yep, there's the idea of putting Bools in a typeclass that allows you to
> (||) functions-returning-Bool-class-instance for example, which I 
> haven't used much but seems like a good idea (though potentially 
> confusing, especially if the Prelude-Bool-specific names are reused)

-- Datatypes having default values
class    Defaults a      where defaultValue :: a
instance Defaults ()     where defaultValue = ()
instance Defaults Bool   where defaultValue = False
instance Defaults [a]    where defaultValue = []
instance Defaults (a->a)               where defaultValue = id
instance Defaults (Maybe a)            where defaultValue = Nothing
instance Defaults (a->IO a)            where defaultValue = return
instance Defaults a => Defaults (IO a) where defaultValue = return defaultValue
instance Num a => Defaults a           where defaultValue = 0

-- Datatypes that can be checked for default value
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)

infixr 3  &&&
infixr 2  |||

a ||| b | isDefaultValue a = b
        | otherwise        = a

a &&& b | isDefaultValue a = defaultValue
        | otherwise        = b

my code contains countless examples of using these funcs:

1. here it is used to conditionally include options in cmdline:
      ["rar", "x", arcname]++
      (isAddDir &&& ["-ad"])++
      (arcdir &&& files &&& ["-ap"++arcdir])++...

2. here it is used to get list of files where current directory may be
specified as "":
   files <- dirList (dirName ||| ".")

3. here it is used to show file basename or full path if basename is empty:
    putStr (takeBaseName file  |||  file)

4. here it's used for conditional code execution:
   do opt_debug command &&& testMalloc

5. here it is used to additionally print amount of bad sectors if it's non-zero:
   putStrLn$ show recoverable_sectors++" recoverable errors "++
            (bad_sectors &&& " and "++show bad_sectors++" bad sectors")

6. here it's used to create tempfile in current directory unless
temporary directory was explicitly specified in --tempdir option
   let filename = (opt_tempdir command ||| ".") </> "$$temp$$"

7. here it is use to apply additional reorder step to sorted list only
if --reorder option was specified
  sorted_diskfiles <- (opt_reorder command &&& reorder) (sort_files command diskfiles)

(reorder has type [String] -> IO [String])

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

More information about the Haskell-Cafe mailing list