Skip to content

Instantly share code, notes, and snippets.

import scala.concurrent.{future, Await}
import scala.concurrent.duration._
import scala.util.{Success, Failure}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.language.postfixOps
object TestFutures {
def testAsyncWork {
val f = future {
Thread.sleep(1000) // simulating work
def query[T](target: String, params: Seq[(String, String)])(fromRespStr: String => T): (Int, Option[T]) = {
executer x (:/(host, port) / target <<? params >:> identity) {
case (200, _, Some(entity), _) => {
val respBodyStr = fromInputStream(entity.getContent()).getLines.mkString
(200, Some(fromRespStr(respBodyStr)))
}
case (status, _, _, _) => (status, None)
}
}
import scala.actors.Actor
import scala.actors.Actor._
import scala.util.Random.shuffle
case class Start(player1: Actor, player2: Actor)
case object Stop
case class Play(coordinator: Actor)
case class Throw(player: Actor, move: String)
echo "Adding ppa:dns/gnu repository"
sudo add-apt-repository -y ppa:dns/gnu
echo ""
echo "Updating package listings"
sudo apt-get update
echo ""
echo "Upgrading gprolog package"
sudo apt-get install -yu gprolog
% Basic bit-wise pattern matching
1> <<Foo,Bar,Baz>> = <<1,2,3>>.
% Some more advanced pattern matching
2> <<R:8,G:8,B:8>> = <<16#BADA55:24>>.
<<"ºÚU">>
% Using the built in bindings command
3> b().
B = 85
% Basic `case` usage
Animal = "dog".
case Animal of
"dog" -> imadog;
"cat" -> imacat;
_ -> whatami % underscore is again wildcard
end.
% Pattern Matching with `case`
DurhamWeather = {cloudy, durham}.
-module(ex_if).
-export([is_42/1, always_true/0]).
% contrived example
is_42(Num) ->
if
Num =:= 42 -> true;
true -> false
end.
% Simple comprehensions (notice the similarity to map?)
% increment
[ X+1 || X <- [1,2,3,4] ].
% powers of two
[ math:pow(2,X) || X <- [1,2,3,4] ].
% Comprehension with list of tuples
CityWeathers = [{cloudy, chicago}, {sunny, florida}, {raining, london}, {cloudy, durham}].
[ case Weather of cloudy -> io:format("~p is cloudy\n", [City]); _ -> false end || {Weather, City} <- CityWeathers ].
% Almost the same thing: using a filter instead of case
% Anonymous functions
One = fun() -> 1 end.
Inc = fun(X) -> X + 1 end.
Add = fun(X,Y) -> X + Y end.
% Aliasing a function/Referencing an external function
AbsAlias = fun erlang:abs/1.
% map/2
Map = fun lists:map/2.
% increment using anon fn
Map(fun(X) -> X + 1 end, [1,2,3,4]).
% find powers of two
PowerOfTwo = fun(X) -> math:pow(2, X) end.
Map(PowerOfTwo, [1,2,3,4]).
% filter/2
Filter = fun lists:filter/2.