Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
davidallsopp / pureio.py
Created June 17, 2014 21:42
Trying to explain Haskell-style pure IO to a Python programmer, in the hope that I will understand it better myself (!).
#
# A crude demo of how IO can be pure yet achieve something.
# All functions are pure, including main(). Only __main__ has effects.
#
class IO:
def __init__(self, f):
self.f = f
def run(self, x):
return self.f(x)
@davidallsopp
davidallsopp / GeoHash.scala
Last active August 29, 2015 14:03
Implementation of geohashing as described at https://en.wikipedia.org/wiki/Geohash
object GeoHash {
import Base32._, Calation._
val LAT_RANGE = (-90.0, 90.0)
val LON_RANGE = (-180.0, 180.0)
// Aliases, utility functions
type Bounds = (Double, Double)
def mid(b: Bounds) = (b._1 + b._2) / 2.0
@davidallsopp
davidallsopp / PropertyTests.scala
Last active June 12, 2025 05:26
Examples of writing mixed unit/property-based (ScalaTest with ScalaCheck) tests. Includes tables and generators as well as 'traditional' tests.
/**
* Examples of writing mixed unit/property-based (ScalaCheck) tests.
*
* Includes tables and generators as well as 'traditional' tests.
*
* @see http://www.scalatest.org/user_guide/selecting_a_style
* @see http://www.scalatest.org/user_guide/property_based_testing
*/
import org.scalatest._
@davidallsopp
davidallsopp / Shrinking.scala
Last active January 30, 2024 13:25
Solutions to the ScalaCheck problem that shrinking failing values may generate invalid values, because the constraints of the generator are not respected. This is for using ScalaCheck from within ScalaTest.
import org.scalatest._
import prop._
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
/**
* Solutions to the ScalaCheck problem that shrinking failing values may generate
* invalid values, because the constraints of the generator are not respected.
*
* See also http://stackoverflow.com/questions/20037900/scalacheck-wont-properly-report-the-failing-case
@davidallsopp
davidallsopp / NoNeedForNull.scala
Last active August 29, 2015 14:05
An explanation of using the Option type in Scala (or the Maybe type in Haskell) rather than null. See also http://speaking-my-language.blogspot.co.uk/2010/08/why-scalas-option-wont-save-you-from.html for futher discussion/argument, and https://gist.github.com/davidallsopp/79fd49840197f3597b72 for an example of representing an object lifecycle in…
// An explanation of using the Option type in Scala rather than null (in languages such as Java)
// The equivalent in Haskell is the Maybe type
// The Option type is for values that might or might not exist - i.e. exactly the use case
// that null fulfills. It has two subtypes: Some[A] and None
// ( where A is a type parameter - i.e. Some is a generic type. )
val yes = Some("Hello world!")
val no = None
@davidallsopp
davidallsopp / Config.scala
Last active March 30, 2016 13:59
Handling stringly-typed configuration (e.g. config files, system properties). This is a Scala IDE worksheet - you'd package up the code differently in a real app.
import scala.language.implicitConversions
object configs {
// Options (e.g. from a config file or system properties), as key-value strings
val opts = Map("min" -> "100", "path" -> "/home/user2")
// Automatically wrap the default values in a Some
// (or can omit this and specify None to indicate lack of a default value)
implicit def wrap[A](a: A) = Some(a)
@davidallsopp
davidallsopp / Employee.scala
Last active August 29, 2015 14:05
A demonstration of representing object lifecycle directly in the type system, to avoid the need for nullable references or Options when a value is not really optional; The value is required at one stage in the lifecycle, and should be entirely absent at another stage. This way, we cannot get null pointer exceptions, and we cannot encounter Optio…
package example
import java.util.Date
object NoNulls {
sealed trait Employee // sealed, so nobody else can create further subclasses
object Employee {
def apply(id: Int, name: String, start: Date=new Date()) = CurrentEmployee(id, name, start) // factory method
@davidallsopp
davidallsopp / tapestry.py
Created September 25, 2014 20:43
Example for code club (needs tweaking for Python 3 though)
import random
import sys
while True:
for i in range(80):
sys.stdout.write(random.choice("\/|-"))
print
@davidallsopp
davidallsopp / music.py
Last active August 29, 2015 14:06
Random "music" for code club
import random
from random import randint
from winsound import Beep
while True:
Beep(randint(200,5000), 250)
letters = 'abcdefghijklmnopqrstuvwxyz '
jumbled = 'jklmnopqrstuvwxyzabcdefghi '
# Long way
#decrypt_map = { }
#encrypt_map = { }
#for x in range(len(encrypted_letters)):
# encrypted_letter = encrypted_letters[x]
# unencrypted_letter = unencrypted_letters[x]
# decrypt_map[unencrypted_letter] = encrypted_letter