Many modern programming languages allow us to handle potentially infinite lists and to perform certain operations on them.
Example [Python]:
EvenSquareNumbers = ( x * x for x in naturals() if x mod 2 == 0 )
Such lists can exist because only elements that are actually required are computed. (Lazy evaluation)
I just wondered out of interest whether it's possible (or even practised in certain languages) to extend the mechanism of lazy evaluation to arithmetics.
Example:
Given the infinite list of even numbers evens = [ x | x <- [1..], even x ]
We couldn't compute
length evens
since the computation required here would never terminate.
But we could actually determine that
length evens > 42
without having to evaluate the whole length
term.
Is this possible in any language? What about Haskell?
Edit: To make the point clearer: The question is not about how to determine whether a lazy list is shorter than a given number. It's about using conventional builtin functions in a way that numeric computation is done lazily.
sdcvvc showed a solution for Haskell:
data Nat = Zero | Succ Nat deriving (Show, Eq, Ord)
toLazy :: Integer -> Nat
toLazy 0 = Zero
toLazy n = Succ (toLazy (n-1))
instance Num Nat where
(+) (Succ x) y = Succ (x + y)
(+) Zero y = y
(*) Zero y = Zero
(*) x Zero = Zero
(*) (Succ x) y = y + (x * y)
fromInteger = toLazy
abs = id
negate = error "Natural only"
signum Zero = Zero
signum (Succ x) = Succ Zero
len [] = Zero
len (_:x') = Succ $ len x'
-- Test
len [1..] < 42
Is this also possible in other languages?