Skip to content

Instantly share code, notes, and snippets.

Advanced Functional Programming with Scala - Notes

Copyright © 2017 Fantasyland Institute of Learning. All rights reserved.

1. Mastering Functions

A function is a mapping from one set, called a domain, to another set, called the codomain. A function associates every element in the domain with exactly one element in the codomain. In Scala, both domain and codomain are types.

val square : Int => Int = x => x * x
val suits = List("H", "D", "C", "S")
val values = List("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
val cards = for (s <- suits; v <- values) yield v + s
def iteration(): Int = {
val shuffledCards = scala.util.Random.shuffle(cards)
val positions = shuffledCards.zipWithIndex.filter(cardWithIdx => cardWithIdx._1 == "QC" || cardWithIdx._1 == "QS").map(_._2 + 1)
positions.last
}
@jb77
jb77 / gist:231f9c0121c60619f3ac
Created March 4, 2015 15:43
Quick hack to extract some base64 encoded strings from a McAfee XML file and print as plain text.
import java.util.Base64
import java.io.PrintWriter
object scratch {
val root = scala.xml.XML.loadFile("""C:\temp\030415022143-030415025143.mpr""")
val names = (root \\ "FilenameCDATA").toList
val base64Names = names.map(_.text)
val decoder = Base64.getDecoder()
val asciiNames = base64Names.map(b64 => new String(decoder.decode(b64)))
@jb77
jb77 / gist:da3b4b5bd7478500552e
Last active August 29, 2015 14:04
Recursive Puzzle Solver
/*
http://richardwiseman.wordpress.com/2014/08/04/answer-to-the-friday-puzzle-269/
OK, onto the puzzle. Can you create a 10-digit number,
where the first digit is how many zeros in the number,
the second digit is how many 1s in the number etc
until the tenth digit which is how many 9s in the number.
*/
def selfReferential(number:String) : Boolean = {
val numsWithIdx=number.zipWithIndex
/*
http://richardwiseman.wordpress.com/2014/08/04/answer-to-the-friday-puzzle-269/
OK, onto the puzzle. Can you create a 10-digit number,
where the first digit is how many zeros in the number,
the second digit is how many 1s in the number etc
until the tenth digit which is how many 9s in the number.
*/
def digitSum(i:Long) = i.toString.toList.map(_.asDigit).sum