Convert IO callback to infinite list

cats-effect tutorial
cats-effect timer example
fs2 infinite stream
flask real time update
cats ioapp example
cats-effect ref
flask update page without refresh
scala fibers

I am using a library that I can provide with a function a -> IO (), which it will call occasionally.

Because the output of my function depends not only on the a it receives as input, but also on the previous a's, it would be much easier for me to write a function [a] -> IO (), where [a] is infinite.

Can I write a function:

magical :: ([a] -> IO ()) -> (a -> IO ())

That collects the a's it receives from the callback and passes them to my function as a lazy infinite list?

This is not exactly what you asked for, but it might be enough for your purposes, I think.

magical :: ([a] -> IO ()) -> IO (a -> IO ())
magical f = do
   list <- newIORef []
   let g x = do
          modifyIORef list (x:)
          xs <- readIORef list
          f xs   -- or (reverse xs), if you need FIFO ordering
   return g

So if you have a function fooHistory :: [a] -> IO (), you can use

main = do
   foo <- magical fooHistory
   setHandler foo -- here we have foo :: a -> IO ()

As @danidaz wrote above, you probably do not need magical, but can play the same trick directly in your fooHistory, modifying a list reference (IORef [a]).

main = do
   list <- newIORef []
   let fooHistory x = do
          modifyIORef list (x:)
          xs <- readIORef list
          use xs   -- or (reverse xs), if you need FIFO ordering
   setHandler fooHistory -- here we have fooHistory :: a -> IO ()

Tips for working with FS2, The snippet above creates an infinite stream of data, emitting the value 1 . Every value we emit is then mapped to convert it to 4 . Effect, IO } type Row = List[​String] trait CSVHandle { def withRows(cb: Either[Throwable,Row] where we do a callback to withRows to enqueue data, and we receive a stream  callback_on_new_best – (Optional[BaseCallback]) Callback to trigger when there is a new best model according to the mean_reward; n_eval_episodes – (int) The number of episodes to test the agent; eval_freq – (int) Evaluate the agent every eval_freq call of the callback.

The IORef solution is indeed the simplest one. If you'd like to explore a pure (but more complex) variant, have a look at conduit. There are other implementations of the same concept, see Iteratee I/O, but I found myself conduit to be very easy to use.

A conduit (AKA pipe) is an abstraction of of program that can accept input and/or produce output. As such, it can keep internal state, if needed. In your case, magical would be a sink, that is, a conduit that accepts input of some type, but produces no output. By wiring it into a source, a program that produces output, you complete the pipeline and then ever time the sink asks for an input, the source is run until it produces its output.

In your case you'd have roughly something like

magical :: Sink a IO () -- consumes a stream of `a`s, no result
magical = go (some initial state)
    go state = do
      m'input <- await
      case m'input of
        Nothing -> return ()  -- finish
        Just input -> do
          -- do something with the input
          go (some updated state)

Cats Effect: IO, For example, you don't need to convert Scala's Future , because you already have a call the callback; task becoming // non-terminating ;-) } // Cancellation logic IO In this example, repeat is a very long running IO (infinite, in fact!) which will If you have a list of IO, and you want a single IO with the result list you can use  You are sharing too many data structures with too many threads, I guess. I think that you should put all handling of the serial device IO for one port into a single thread and put a synchronized command/data queue between the IO thread and all client threads. Have the IO thread watch out for commands/data in the queue.

Control.Concurrent.Chan does almost exactly what I wanted!

import Control.Monad           (forever)
import Control.Concurrent      (forkIO)
import Control.Concurrent.Chan

setHandler :: (Char -> IO ()) -> IO ()
setHandler f = void . forkIO . forever $ getChar >>= f

process :: String -> IO ()
process ('h':'i':xs) = putStrLn "hi" >> process xs
process ('a':xs)     = putStrLn "a" >> process xs
process (x:xs)       = process xs
process _            = error "Guaranteed to be infinite"

main :: IO ()
main = do
  c <- newChan
  setHandler $ writeChan c
  list <- getChanContents c
  process list

Asynchronous updates to a webpage with Flask and , For communication, “events” are triggered by either the server or connected clients, and corresponding callback functions are set to execute when​  What would be the best way to convert/wrap a "classic" asynchronous method that uses a callback to something that returns a (awaitable) Task? For example, given the following method: public void GetStringFromUrl(string url, Action<string> onCompleted); The only way I know of to wrap this into a method returning a task is:

This seems like a flaw in the library design to me. You might consider an upstream patch so that you could provide something more versatile as input.

Observable, Converts a Node.js-style callback API to a function that returns an Observable. public static Convert an infinite iterable (from a generator) to an Observable. function* List of DOM Nodes, returned for example by document.​querySelectorAll  IO_OVS_CALLBACK ( a reference to IF_WD_OVS). This instance has method named set_output_table, which need to be used to populate the possible entries. Declare a local structure and internal table to hold the F4 values to be displayed on screen. As always, now we will need to write a select statement to populate the internal table.

Node.js: How even quick async functions can block the Event-Loop , A typical Node.js app is basically a collection of callbacks that are executed quick to complete as all other pending callbacks are waiting for their turn. If you'​ll scroll up to look again, you will recognize the RunMicrotasks() in the stack) and visibility of what happens with other pending routines and IO. You may provide callback URL, when starting the conversion. This URL get notified when conversion is finished (either successful or not). If the callback URL did not respond within 10 seconds or the HTTP response code >= 500 request will be retried for up to 5 times with an interval of 10 seconds.

Infinite Scroll · Extras, Everything else about Infinite Scroll: module loaders, loading JSON, extra demos. main.js var InfiniteScroll = require('infinite-scroll'); var infScroll = new that data into template var itemsHTML = template.compile( data ); // convert to jQuery object '.page-load-status', }); // use event for v2 callback $container.on( 'append​. 1,171,798 views. Infinite Lists Reacts To MYSTERY RIDDLES. INCREDIBLE CAKES That Look Like Everyday Objects! 6,605,097 views 3 months ago. 😳NEW YOUTH Hoodies OUT NOW😳

async - Documentation, The iteratee is called with an item from the list, and a callback for when it has finished. concurrency, number <optional>, Infinity data callback(null, 'data', '​converted to array'); }, make_folder: function(callback) { // async code to else { doSomeIO(arg, callback); // this IO would be asynchronous } } // this has a risk of stack  Return from a function. The return value for a call to a property or method can be set to the result of a function. This allows more complex logic to be put into the substitute. Although this is normally a bad practice, there are some situations in which it is useful.

  • "Because the output of my function depend not only on the a it receive as input" - unfortunately you can't do that in Haskell, because it's referentially transparent. That is, the output value of a function depends only on the parameters passed to it.
  • This is true for pure functions, but because this is in the IO monad I can store state between calls. This is what I am doing manually at the moment and are trying to avoid