The following code computes numerical trees1 for quantifiers of type Quant
, which is similar to the type of functions all
and any
:
treeOfNumbers :: [(Integer, Integer)]
treeOfNumbers =
[0..] >>= \ row ->
let
inc = [0 .. row]
dec = reverse inc
in
zip dec inc
type Quant = (Integer -> Bool) -> [Integer] -> Bool
check :: Quant -> (Integer, Integer) -> Bool
check q (m,n) =
q (\ d -> d - m > 0) [1 .. domN]
where
domN = m + n
genTree :: Quant -> [(Integer, Integer)]
genTree q =
filter (check q) treeOfNumbers
For example, the value for take 10 $ genTree all
is
[(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(0,8),(0,9)]
This code, however, appears to cause memory leaks. With ghci’s heap limited at 100M, genTree all
is interrupted around (0,1600)
. With the limit at 500M, it stops around (0,3950)
, after having become very slow.
How can this be improved? I have limited experience with Haskell, and can only guess that perhaps my implementation of treeOfNumbers
is the culprit; check
works for large values without any problem.
1See Computational Semantics with Functional Programming (Jan van Eijck and Christina Unger), Cambridge University Press, 2010, pp. 157–159.