Search code examples
haskelliosequence

Haskell sequence of IO actions processing with filtration their results in realtime+perfoming some IO actions in certain moments


I want to do some infinite sequence of IO actions processing with filtration their results in realtime+perfoming some IO actions in certain moments: We have some function for reducing sequences (see my question haskell elegant way to filter (reduce) sequences of duplicates from infinte list of numbers):

f :: Eq a => [a] -> [a]
f = map head . group

and expression

join $ sequence <$> ((\l -> (print <$> l)) <$> (f <$> (sequence $ replicate 6 getLine)))

if we run this, user can generate any seq of numbers, for ex:

1
2
2
3
3
"1"
"2"
"3"
[(),(),()]

This means that at first all getLine actions performed (6 times in the example and at the end of this all IO actions for filtered list performed, but I want to do IO actions exactly in the moments then sequencing reduces done for some subsequences of same numbers.

How can I archive this output:

1     
2
"1"
2     
3
"2"        
3
3
"3"
[(),(),()]

So I Want this expression not hangs:

 join $ sequence <$> ((\l -> (print <$> l)) <$> (f <$> (sequence $ repeat getLine)))

How can I archive real-time output as described above without not blocking it on infinite lists?


Solution

  • I found a nice solution with iterateUntilM

    iterateUntilM (\_->False) (\pn -> getLine >>= (\n -> if n==pn then return n else (if pn/="" then print pn else return ()) >> return n) ) ""
    

    I don't like some verbose with

    (if pn/="" then print pn else return ())
    

    if you know how to reduce this please comment)

    ps. It is noteworthy that I made a video about this function :) And could not immediately apply it :(