Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
davidallsopp / unfold.scala
Last active December 23, 2015 23:39
Converting integers into Roman numerals. An example of defining and using the "unfold" higher-order function in Scala (as an Eclipse Scala Worksheet).Adapted from http://daily-scala.blogspot.co.uk/2009/09/unfoldleft-and-right.html and http://www.scala-blogs.org/2008/01/roman-numerals-in-scala.html for the romanize example. See also Haskell versi…
object unfold {
def unfoldRight[A, B](seed: B)(f: B => Option[(A, B)]): List[A] = f(seed) match {
case Some((a, b)) => a :: unfoldRight(b)(f)
case None => Nil
}
def unfoldLeft[A, B](seed: B)(f: B => Option[(B, A)]) = {
def loop(seed: B)(ls: List[A]): List[A] = f(seed) match {
case Some((b, a)) => loop(b)(a :: ls)
@davidallsopp
davidallsopp / birthday.scala
Last active December 23, 2015 23:48
Happy Birthday in Scala - a couple of variations
object birthday {
1 to 4 map { i => "Happy Birthday " + (if (i == 3) "dear Scala" else "to you") } foreach println
(1 to 4).foldLeft("")((r,c) => r + ("\nHappy Birthday " + (if (c == 3) "dear Scala" else "to you")))
}
@davidallsopp
davidallsopp / findfiles.scala
Created September 26, 2013 09:53
Recursively find files from a starting directory
def findFiles(d: File): Array[File] = {
val (dirs, files) = d.listFiles.partition(_.isDirectory)
files ++ dirs.flatMap(findFiles)
}
@davidallsopp
davidallsopp / ProxyTester.scala
Last active December 24, 2015 01:59
Simple demo of checking HTTP proxy settings and/or downloading text or HTML pages in Scala, with equivalent code in Python for comparison
import scala.sys.SystemProperties
import scala.io.Source.fromURL
object ProxyTester extends App {
// Uncomment if you are behind a proxy, then edit the IP and port to match your proxy
// val props = new SystemProperties
//props("http.proxyHost") = "localhost"
//props("http.proxyPort") = "8080"
// Uncomment to see all the system properties including proxy settings
@davidallsopp
davidallsopp / phone_regex.scala
Last active April 27, 2018 13:44
Scala regex and pattern matching example - phone numbers
import scala.util.matching.Regex
object regex {
val number = "07923 874123" //> number : String = 07923 874123
val pattern = """(\d{5})[ -]?(\d{6})""" //> pattern : String = (\d{5})[ -]?(\d{6})
number.matches(pattern) //> res0: Boolean = true
// Compiled pattern
@davidallsopp
davidallsopp / letterfreq.scala
Created September 29, 2013 11:25
Letter frequency one-liner in Scala.
"zoology".groupBy(identity).mapValues(_.length)
// Map(y -> 1, g -> 1, l -> 1, o -> 3, z -> 1)
// identity is equivalent to x => x
@davidallsopp
davidallsopp / retry.scala
Created October 12, 2013 20:57
Creating convenient syntax for retrying an unreliable operation, using Try, currying, call-by-name (and @tailrec, if you really need lots of retries!) This is a Scala Eclipse worksheet, so won't run standalone without a minor tweak.
import scala.annotation.tailrec
import scala.util.Random
import scala.util.{ Try, Success, Failure }
object retry {
{ // extra block is a workaround for Scala worksheet bug with @tailrec
@tailrec
def withRetry[T](attempts: Int)(f: => T): T = {
println("Attempts remaining: " + attempts)
@davidallsopp
davidallsopp / bitsAndBytes.scala
Last active December 25, 2015 23:09
Playing around with bytes and bits - based on a couple of forum threads on the Sept 2013 "Functional Programming Principles in Scala" MOOC on Coursera (progfun).
val bytes = List[Byte](0, 1, -1, 127, -128)
def toBits(b: Byte) = 0 to 7 map (b >> _ & 1)
val bits = bytes flatMap toBits
// Note: least-significant bit on the left!
// List(0, 0, 0, 0, 0, 0, 0, 0,
// 1, 0, 0, 0, 0, 0, 0, 0,
// 1, 1, 1, 1, 1, 1, 1, 1,
// 1, 1, 1, 1, 1, 1, 1, 0,
@davidallsopp
davidallsopp / SwingBuilder.scala
Last active December 26, 2015 09:09
When writing Swing GUI code (in particular) we often have many repetitive calls to the same object. When using Swing from Scala, it would be nice to remove that duplication:
import javax.swing.JCheckBox
object SwingBuilder {
// Instead of this:
val checkbox = new JCheckBox()
checkbox.setText("Hello")
checkbox.setAlignmentX(0.0f)
checkbox.setLocation(0, 100)
@davidallsopp
davidallsopp / diamond.scala
Created November 5, 2013 16:41
Linearization of traits in Scala to handle the diamond inheritance problem. Adapted from http://jim-mcbeath.blogspot.co.uk/2009/08/scala-class-linearization.html It now seems OK to refer to indirect parent traits, i.e. super[A], which apparently wasn't possible at the time of the original article.
// Adapted from http://jim-mcbeath.blogspot.co.uk/2009/08/scala-class-linearization.html
object diamond {
class A { def t = 1 }
// super refers to the next trait in the linearization, not necessarily to A
trait B extends A { override def t = super.t + 1 }
trait C extends A { override def t = super.t * 2 }
// Linearises to (D1, C, B, A)