Skip to content

Instantly share code, notes, and snippets.

@mattyw
mattyw / pierre.exs
Last active December 18, 2015 04:19
Walk the line from http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line done in elixir. The first version shows the advantage of the pipe operator. The update shows us testing for preconditions with 'when' and also using patten matching to make the landleft and right functions easier to read.
# Inspired by:
# http://learnyouahaskell.com/a-fistful-of-monads#walk-the-line
# Put simply, pierre is a tight rope walker. birds land on the left
# or right of his pole. If the difference is > 3 he falls off
ExUnit.start
defmodule WalkTheLine do
use ExUnit.Case
package main
import "fmt"
type BasketItem struct {
Id string
Price int
}
type Basket struct {
package main
import (
"encoding/json"
"fmt"
)
var jsonStr = []byte(`
{
"things": [
@mattyw
mattyw / under.go
Created December 30, 2012 23:23
under in go
package main
import (
"fmt"
"math"
)
//Setup some types for functions we want to pass around
type unaryFloat func(float64) float64
type binaryFloat func(float64, float64) float64
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a := 0
b := 1
@mattyw
mattyw / euler_14.clj
Created June 8, 2012 08:55
Project Euler Problem 14 in Clojure
(defn collatz [n]
(if (even? n)
(/ n 2)
(inc (* 3 n))))
(defn collatz-seq [start ls]
(let [next-number (collatz start)]
(if (= start 1)
(conj ls 1)
(collatz-seq next-number (conj ls start)))))
@mattyw
mattyw / pythag.clj
Created January 8, 2012 06:01
Pythagoras' theorem using J's under idiom in Clojure. See (http://mattyjwilliams.blogspot.com/2012/01/under-new-idiom-from-j-language.html)
(defn under [verb, obverse, func x y]
(obverse (func (verb x) (verb y))))
(defn sqrt [x]
(Math/sqrt x))
(defn square [x]
(Math/pow x 2))
(defn pythagoras [x y]
@mattyw
mattyw / under.clj
Created January 4, 2012 13:54
J's under conjecture in clojure
;;Will Suffer from rounding errors - but ok for an example
(defn under [verb, obverse, func x y]
(obverse (func (verb x) (verb y))))
(defn log [x]
(Math/log x))
(defn exp [x]
(Math/exp x))
@mattyw
mattyw / gol.hs
Created December 3, 2011 15:40 — forked from nschmoller/gol.hs
Game of life in Haskell (in 45 minutes)
zeroes 0 = []
zeroes n = [0] ++ (zeroes (n-1))
foo x y z= zipWith (+) (zipWith (+) x y) z
grid_neighbours l =
let top = map inc_neighbours ( [(zeroes (length (head l)))] ++ (take (length l) l) )
bottom = map inc_neighbours ((drop 1 l) ++ [(zeroes (length (head l)))])
current = map neighbours l
in zipWith3 foo top bottom current
;; mattyw's solution to Reverse a Sequence
;; https://4clojure.com/problem/23
(defn reverse-func [seq]
(reduce (fn [a b] (cons b a)) '() seq))
(println (= (reverse-func [1 2 3 4 5]) [5 4 3 2 1]))