Skip to content

Instantly share code, notes, and snippets.

@g-pechorin
Last active November 21, 2022 15:06
Show Gist options
  • Save g-pechorin/a6d6f3f72931362bef035b2a9d5c5b04 to your computer and use it in GitHub Desktop.
Save g-pechorin/a6d6f3f72931362bef035b2a9d5c5b04 to your computer and use it in GitHub Desktop.
package peterlavalle.pg3
import peterlavalle.{E, *}
/**
*
* @param create some function to open a resource
* @tparam I the full key needed to open a resource (file or socket, parapmeters, etc)
* @tparam V the resource handle and any key or whatever that's needed
*/
class Sleeper[I, V](create: I => E[V]) {
/**
* an empty item, which uses this create but doesn't have anything open yet
*/
object Initial extends Dreamer {
override def map[O](f: List[V] => E[O]): E[O] = f(Nil)
}
/**
* an instance with some count of open things
*/
trait Dreamer {
/**
* open something and return the next state and the created handle
*
* @param i the key/parameters to open the resource
* @return the next state and the handle to whatever we made
*/
def bind(i: I): E[(Dreamer, V)] =
for {
v <- create(i)
} yield {
Dream(v, this) -> v
}
/**
* do something with all opened resource handles (FIFO)
*
* @param f the function to build some result
* @tparam O
* @return the result we built - possibly a runnable instance of the AI that ties together all the resource handles
*/
def map[O](f: List[V] => E[O]): E[O]
private class Dream(v: V, from: Dreamer) extends Dreamer {
override def map[O](f: List[V] => E[O]): E[O] =
for {
l <- from
} yield {
f(l :+ v)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment