Skip to content

Instantly share code, notes, and snippets.

View mmollaverdi's full-sized avatar

Mehdi Mollaverdi mmollaverdi

  • Melbourne
View GitHub Profile
$ gradle create
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :compileKotlin
w: file:///Users/mmollaverdi/projects/cash-monorepo-builder/src/main/kotlin/commands/create/Main.kt:11:10 Parameter 'args' is never used
> Task :create
/Users/mmollaverdi/projects/monorepo-staging/cash-server git init .
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
@mmollaverdi
mmollaverdi / Function1Applicative.js
Last active June 13, 2017 13:09
Implementation of Applicatives for functions with arity of 1 in Javascript
// Read on Applicatives here: https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch10.html
function function1(f) {
return {
ap: g => function1(x => f(x)(g.apply(x))),
apply: f
}
}
Function1 = {
import scala.concurrent.Future
def fetchSystem(id: String): Future[System] = ??? // do some magic to get system data from an API in a different galaxy
def fetchSystemStatus(id: String): Future[SystemStatus] = ??? // do some other magic to get system status from another API
trait Applicative[F[_]] {
def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
def pure[A](x: A): F[A]
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = {
val fCurried: A => B => C = f.curried
val fbc: F[B => C] = ap[A, (B => C)](pure(fCurried))(fa)
ap[B, C](fbc)(fb)
}
implicit val TaskApplicative = new Applicative[Task] {
override def ap[A, B](ff: Task[A => B])(fa: Task[A]): Task[B] = Task.mapBoth(ff, fa)((f, a) => f(a))
override def pure[A](x: A): Task[A] = Task.now(x)
}
implicit val OptionApplicative = new Applicative[Option] {
def ap[A, B](ff: Option[A => B])(fa: Option[A]): Option[B] = for {
f <- ff
a <- fa
} yield f(a)
def pure[A](a: A): Option[A] = Option(a)
}
trait Applicative[F[_]] {
def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
def pure[A](x: A): F[A]
}
getSystemStatusInfo(fetchSystem("consumer_desktop"), fetchSystemStatus("consumer_desktop"))
def getSystemStatusInfo[F[_]: Applicative](fetchSystem: F[System], fetchSystemStatus: F[SystemStatus]): F[SystemStatusInfo] = {
Applicative[F].map2(fetchSystem, fetchSystemStatus)((system, systemStatus) => SystemStatusInfo(system, systemStatus))
}
trait Applicative[F[_]] {
def map2[A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C] = ??? // ...
}