Skip to content

Instantly share code, notes, and snippets.

@miguel-vila
miguel-vila / ml-hw2
Last active December 25, 2015 11:39
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
@miguel-vila
miguel-vila / TypeclassPattern.scala
Created October 12, 2013 19:08
Scala's Typeclass pattern
trait MeasureTypeClass[A]{
def measure(a: A) : Int
}
object TypeClassExample{
def genericMeasure[A : MeasureTypeClass](value: A): Int = {
val measurer = implicitly[MeasureTypeClass[A]]
measurer.measure(value)
}
@miguel-vila
miguel-vila / FutureAndOptionComposition.scala
Last active December 25, 2015 06:09
The setup: four types A,B, C and D, an initial value x of the type Future[Option[A]] and three functions: f1: A => Option[B] , f2: B => Future[Option[C]] and f3: C => D. How can you write a for comprehension starting with x that results in a value of the type Future[Option[D]] that would be the "composition" of the three functions? (thanks to Huw:
import scalaz.contrib.std.FutureInstances // Dependency: scalaz-contrib
import scalaz.{ Monad , OptionT } // Dependency: scalaz
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class FutureAndOptionComposition[A, B, C, D]
extends FutureInstances
// The FutureInstances trait has a method which creates a Monad instance
// for Future which is used implicitly by the OptionT
{