Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating output in a running haskell program

Coming from (SWI) Prolog I find it very difficult to have Haskell give output on the fly.

The simplest example, I'd like Haskell to print something on every iteration:

fac 0 = 1  
fac n = fac ( n-1 ) * n

Or I would like to get output from a program that never halts...

-- A possible halt statement...  
-- find_primes l 100 = l  
find_primes l n = if ( is_prime l n ) then find_primes nn s else find_primes l s  
where   s = n + 1
nn = n:l

is_prime :: Integral a => [a] -> a -> Bool  
is_prime [] n = True  --print the prime number on the fly    
is_prime (h:t) n = if ( r /= 0 ) then is_prime t n else False  
where r =  n mod h

Prelude> find_primes [ ] 2

like image 279
Ihmahr Avatar asked Dec 06 '22 19:12

Ihmahr


1 Answers

You have three options:

First: spread IO everywhere and write in Haskell as in fancy imperative language.

fac 0 = putStrLn "0! = 1" >> return 1
fac n = do
    x <- fac (n - 1)
    let r = x * n
    putStrLn $ show n ++ "! = " ++ show r
    return r

Second: use unsafePerformIO and its derivatives (e.g. Debug.Trace). Useful for shooting yourself in the foot and debugging purposes.

Third: instead of mixing I/O and computation in the code, lazily generate a [potentially infinite] data structure containing intermediate results in a pure function and consume it separately. For example, the infinite list of factorials can be written as:

facs = scanl (*) 1 [1..]

And consumed as follows to yield the same result as in calling fac 10 in the example above:

forM_ (take 11 $ zip [0..] facs) $ \(i, x) ->
    putStrLn $ show i ++ "! = " ++ show x
like image 94
rkhayrov Avatar answered Dec 09 '22 14:12

rkhayrov