Skip to content

Instantly share code, notes, and snippets.

View calvinlfer's full-sized avatar
🥳

Calvin Lee Fernandes calvinlfer

🥳
View GitHub Profile
@calvinlfer
calvinlfer / funwithtypeclasses.scala
Last active August 27, 2016 04:28
Showing how to take advantage of typeclasses in Scala using implicits along with using implicit classes to make fancy symbols appear almost native to the language in conjunction with making use of the typeclass implementations inside the implicit classes
// typeclass framework (really a Monoid + SemiGroup)
trait Num[A] {
val zero: A
def add(x: A, y: A): A
}
// provide default typeclass implementations in the companion object so when used
// it brings some default typeclass implementations with it
object Num {
// object way
@calvinlfer
calvinlfer / functor-monad-typeclass-understanding.scala
Created September 1, 2016 23:29
Implementing the Monad and Functor typeclass in Scala and also looking into Point Free
import scala.language.higherKinds
// Functor typeclass - it abstracts over higher kinded types (functions at the type level)
trait Functor[HigherKindedType[_]] {
def map[A, B](functorA: HigherKindedType[A])(mapper: A => B): HigherKindedType[B]
def unit[A](simpleA: => A): HigherKindedType[A]
}
// Monad typeclass - it also abstracts over higher kinded types (functions at the type level)
// A Monad is also a Functor
@calvinlfer
calvinlfer / functor-monad-typeclass-understanding.scala
Last active September 2, 2016 04:33
Implementing the Monad and Functor typeclass in Scala and also looking into Point Free, you can run this in a Scala worksheet
import scala.language.higherKinds
// Functor typeclass - it abstracts over higher kinded types (functions at the type level)
trait Functor[HigherKindedType[_]] {
def map[A, B](functorA: HigherKindedType[A])(mapper: A => B): HigherKindedType[B]
def unit[A](simpleA: => A): HigherKindedType[A]
}
object Functor {
// A Functor typeclass implementation for the List Higher Kinded Type (function at the type level)
@calvinlfer
calvinlfer / request-logging.scala
Last active November 15, 2016 18:25 — forked from adamw/log.scala
Logging request duration, path, status code using Akka HTTP
// Setup
val rejectionHandler = RejectionHandler.default
val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
@calvinlfer
calvinlfer / example.scala
Last active October 21, 2016 19:13
Abstracts over an SQS message with SNS wrapping and safely converts it to a case class using the Try monad
import com.amazonaws.services.sqs
import org.json4s.NoTypeHints
import org.json4s.ext.{JavaTypesSerializers, JodaTimeSerializers}
import org.json4s.jackson.Serialization
import scala.collection.JavaConverters._
import scala.util.Try
case class SQSMessage[T](messageId: String, receiptHandle: String, md5OfBody: String, body: T,
attributes: Map[String, String], md5OfAttributes: String)
@calvinlfer
calvinlfer / example.scala
Created October 28, 2016 00:31
Example SQS interactions with AWS-Wrap
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import com.amazonaws.services.sqs.AmazonSQSAsyncClient
import com.amazonaws.services.sqs.model.{ReceiveMessageResult, SendMessageResult}
import com.github.dwhjames.awswrap.sqs.AmazonSQSScalaClient
import scala.collection.JavaConverters._
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
import scala.concurrent.duration._
implicit val ec = scala.concurrent.ExecutionContext.global

I think the better approach is to know what is a Functor before asking about Monads.

A Functor is a Higher Kinded Type/Type Constructor/Function at the type level that has a certain shape (that is, it implements a map function). A Functor is also what's known as a typeclass. A Monad is also a typeclass

Typeclasses are a form of ad-hoc polymorphism that let you add functionality to existing code that you may or may not have written.

Here's is the basic definition of a Functor

trait Functor[F[_]] {
 def map[A, B](fa: F[A])(f: A => B): F[B]
@calvinlfer
calvinlfer / recursive-sort.scala
Last active November 20, 2016 21:00
Generically sort elements that have a concept of ordering using recursion
def sort[T](input: List[T])(implicit ordering: Ordering[T]): List[T] = {
def inner(input: List[T], output: List[T]): List[T] =
(input, output) match {
case (Nil, out) => out
case (head :: tail, Nil) => inner(tail, head :: Nil)
case (iHead :: iTail, oHead :: oTail) if ordering.lteq(iHead, oHead) =>
inner(iTail, iHead :: oHead :: oTail)
@calvinlfer
calvinlfer / merge-sort.scala
Created November 20, 2016 20:51
Generic merge sort based on elements having an Ordered typeclass implementation
def mergeSort[T](list: List[T])(implicit ordering: Ordering[T]): List[T] = {
def merge(l: List[T], r: List[T]): List[T] =
(l, r) match {
case (lHead:: lTail, rHead :: rTail) if ordering.lteq(lHead, rHead) => lHead :: merge(lTail, r)
case (lHead:: lTail, rHead :: rTail) => rHead :: merge(l, rTail)
case (x, Nil) => x
case (Nil, y) => y
@calvinlfer
calvinlfer / quick-sort.scala
Last active May 7, 2019 20:54
Generic Quick Sort in Scala
def quickSort[T](list: List[T])(implicit o: Ordering[T]): List[T] =
list match {
case Nil => Nil
case (head :: tail) =>
// select head as the pivot point
val pivot = head
val (lessThanPivot, greaterThanPivot) = tail.partition(e => o.lteq(pivot, e))
quickSort(lessThanPivot) ::: pivot :: quickSort(greaterThanPivot)
}