0fc3f6f43b7445528ce574fb0261f1cf117fdb1a
[haskell-directory.git] / Data / Generics / Counts.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Generics.Counts
4 -- Copyright   :  (c) The University of Glasgow, CWI 2001--2003
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable
10 --
11 -- "Scrap your boilerplate" --- Generic programming in Haskell 
12 -- See <http://www.cs.vu.nl/boilerplate/>.
13 --
14 -----------------------------------------------------------------------------
15
16 module Data.Generics.Counts ( 
17
18         -- * Generic operations for counting terms
19         glength,
20         gcount,
21         gnodecount,
22         gtypecount
23
24  ) where
25
26 ------------------------------------------------------------------------------
27
28
29 import Data.Generics.Basics
30 import Data.Generics.Aliases
31 import Data.Generics.Schemes
32
33
34 ------------------------------------------------------------------------------
35 --
36 --      Generic operations for counting terms
37 --
38 ------------------------------------------------------------------------------
39
40
41 -- | Count the number of immediate subterms of the given term
42 glength :: GenericQ Int
43 glength = length . gmapL (const ())
44
45
46 -- | Determine the number of all suitable nodes in a given term
47 gcount :: GenericQ Bool -> GenericQ Int
48 gcount p =  everything (+) (\x -> if p x then 1 else 0)
49
50
51 -- | Determine the number of all nodes in a given term
52 gnodecount :: GenericQ Int
53 gnodecount = gcount (const True)
54
55
56 -- | Determine the number of nodes of a given type in a given term
57 gtypecount :: Typeable a => (a -> ()) -> GenericQ Int
58 gtypecount f = gcount (False `mkQ` (const True . f))