We all know about the Fibonacci sequence. Some of us also know a song that uses it to achieve a spiraling feeling (yes, Tool fans!).
In Haskell:
fib 1 = 0
fib 2 = 1
fib x = fib (x - 1) (x - 2)| {-# LANGUAGE NoImplicitPrelude #-} | |
| module Rng where | |
| import GHC.Show (Show) | |
| import GHC.Base (Eq, ($)) | |
| import GHC.Num ((*), (+), Integer) | |
| import GHC.Float (Float, Double) | |
| import GHC.Real (fromIntegral, (/)) | |
| import GHC.Enum (maxBound) | |
| import Data.Int (Int64, Int32, Int16, Int8) |
| data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday | |
| deriving (Eq, Ord, Show, Read, Bounded, Enum) | |
| -- and that's it. we have everything we need | |
| -- david@mac:~% stack ghci | |
| -- λ> Monday == Tuesday | |
| -- False | |
| -- λ> Monday == Monday | |
| -- True | |
| -- λ> Tuesday > Monday |
| #!/usr/bin/env node | |
| 'use strict' | |
| var mysql = require('mysql') | |
| var fs = require('fs') | |
| var path = require('path') | |
| function exitOnError (f) { | |
| return function (err) { |
| 'use strict' | |
| var crypto = require('crypto') | |
| var promise = Promise.resolve() | |
| var data = [] | |
| for (var i = 0; i < 1e5; ++i) { | |
| promise = promise.then(function () { | |
| return new Promise(function (resolve, reject) { |
We all know about the Fibonacci sequence. Some of us also know a song that uses it to achieve a spiraling feeling (yes, Tool fans!).
In Haskell:
fib 1 = 0
fib 2 = 1
fib x = fib (x - 1) (x - 2)As a rookie Haskeller coming from imperative languages I am still
often shocked how elegantly mathematical problems can be expressed in this
great language. Last time a wrote a blogpost about recursion.
As an example, I presented the
Relation type and implemented an operation to it I called join. If you are
familiar with relational algebra you might have recognized that this is a
specific case of equijoin,
where you join pairs so that the first pair's second element matches the second
pair's first element.
I was thinking about a more complex problem I could solve with this toolkit, one
| #/usr/bin/env sh | |
| function killport() { | |
| lsof -i :$1 | tail -n 1 | awk '{ printf $2 }' | xargs kill -9 | |
| } |
| function dfs (vertex, visited) { | |
| if (visited.indexOf(vertex.id) !== -1) { // cut visited nodes | |
| return null | |
| } | |
| if (!vertex.children) { // leaf, return its value | |
| return { id: vertex.id, sum: vertex.value } | |
| } else { // inner node, traverse leaves and aggregate their values | |
| var sum = 0 | |
| var childSums = [] | |
| for (var child in vertex.children) { |
Disclaimer: This is a satire, and not meant to be taken any more seriously than Java itself. It is not about Java 8 streams. This satire just shows how easy is to define a very complex endless stream functionally in Java using lambdas.
In Scala:
def naturals: Stream[Int] = 0 #:: naturals.map(_ + 1)