Skip to content

Instantly share code, notes, and snippets.

View JoolsF's full-sized avatar

Julian Fenner JoolsF

  • London
View GitHub Profile
@JoolsF
JoolsF / Monad1.scala
Created November 5, 2016 15:02
Very basic monad explanation
/**
* Simple Monad
*
* The key abstraction is the flatMap, which binds the computation through chaining.
* Each invocation of flatMap returns the same data structure type (but of different value),
* that serves as the input to the next command in chain. In the above snippet, flatMap
* takes as input a closure (SomeType) => List[AnotherType] and returns a List[AnotherType].
* The important point to note is that all flatMaps take the same closure type as input and
* return the same type as output. This is what "binds" the computation thread - every item
* of the sequence in the for-comprehension has to honor this same type constraint.
@JoolsF
JoolsF / random_filename.scala
Created August 18, 2016 13:00
Random filename generator
import scala.util.Random
/**
* Generates a random string
* Takes an optional prefix and includes timestamp with milisecond accuracy
* To ensure uniqueness, if two strings are requested less than one millisecond apart
* a random string is appended to the end of the string of minimum length 8
*/
def getRandomFileName(prefix: String = "", i: Int = 8) = {
require(i <= 8)
@JoolsF
JoolsF / basic_s3_client.scala
Last active August 16, 2016 14:13
Basic s3 client example
package foo
import java.io.ByteArrayInputStream
import com.amazonaws.ClientConfiguration
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{GetObjectRequest, GroupGrantee, ObjectMetadata, Permission}
import com.typesafe.config.ConfigFactory
@JoolsF
JoolsF / stream_example1.scala
Created August 3, 2016 21:56
Streams example - fibonacci and factorial
lazy val fibs: Stream[BigInt] =
BigInt(0) #::
BigInt(1) #::
fibs.zip(fibs.tail).map { n => n._1 + n._2 }
lazy val N: Stream[BigInt] = BigInt(1) #:: N.map(_ + 1)
lazy val fac: Stream[BigInt] = BigInt(1) #:: fac.zip(N).map(a => a._1 * a._2)
fibs take 10 foreach println
fac take 10 foreach println
@JoolsF
JoolsF / akka_http_setup_basic.scala
Last active July 26, 2016 12:37
Akka HTTP basic setup
import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.actor.ActorSystem
/**
* Basic akka http setup
* Test with
* curl localhost:9000/ping
@JoolsF
JoolsF / future_example1.scala
Created July 24, 2016 14:46
Future example 1
import scala.util.{Failure, Success}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Computation 1 depends on nothing
* Computation 1b depends on result of 1
* Computation 2 depends on nothing
*
* Computation 1b may thrown an exception
@JoolsF
JoolsF / either_example1.scala
Created July 24, 2016 13:53
Exception handling with Either 1
import scala.util.control.Exception._
val r = new java.util.Random
def randomBoolean(exceptionChance: Int) = r.nextInt(exceptionChance) == 0
def handling[Ex <: Throwable, T](exType: Class[Ex])(block: => T): Either[Ex, T] =
catching(exType).either(block).asInstanceOf[Either[Ex, T]]
def exceptionOrString = if(randomBoolean(4)) throw new RuntimeException("This is a runtime exception") else "Phew! You got a string"
@JoolsF
JoolsF / try_example1.scala
Created July 23, 2016 15:38
Try examples 1
import scala.util.Try
val r = new java.util.Random
def randomBoolean = r.nextInt(8) != 0
def stringOrException = if (randomBoolean) "Hello" else throw new RuntimeException
def stringOrException2(string: String) = if(randomBoolean) s"$string world" else throw new ArithmeticException()
def stringOrException3(string: String) = if(randomBoolean) s"$string human" else throw new NullPointerException
val getString: String = Try(stringOrException).getOrElse("There was a problem getting the string") // Hello
@JoolsF
JoolsF / partial_func_example1.scala
Created July 23, 2016 14:38
Partial function example 1
/**
* Partial Functions
* When a function is only defined for a specific input.
*/
val between3and10: (String, Int) => Boolean = {case (_, num) => num >= 3 && num <= 10}
val wordFrequencies = ("habitual", 6) :: ("and", 56) :: ("consuetudinary", 2) ::
("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil
wordFrequencies.filter{case (s,i) => between3and10(s,i) }.map(_._1) //res0: List[String] = List(habitual, homely)
@JoolsF
JoolsF / apply_unapply.scala
Created July 23, 2016 14:15
UnapplySeq Example
/**
* For regular parameters / fixed arity these are the apply constructs and unapply de-structures:
*/
object S {
def apply(a: A):S = ... // makes a S from an A
def unapply(s: S): Option[A] = ... // retrieve the A from the S
}
val s = S(a)
s match { case S(a) => a }