Skip to content

Instantly share code, notes, and snippets.

View akhileshs's full-sized avatar

Akhilesh Srikanth akhileshs

  • San Francisco, CA
View GitHub Profile
@akhileshs
akhileshs / qsort.scala
Created April 3, 2015 12:45
simple quick sort
scala> def qsort(xs: List[Int]): List[Int] = {
| if (xs.length <= 1) xs
| else {
| val pivot = xs(xs.length / 2)
| qsort(xs filter (_ < pivot)) ++ List(pivot) ++ qsort(xs filter (_ > pivot))
| }
| }
qsort: (xs: List[Int])List[Int]
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
factorial :: Integer -> Integer
factorial n = product [1..n]
lucky :: (Integral a) => a -> String
lucky 9 = "Lucky number nine!"
lucky x = "Sorry, you're out of luck!"
@akhileshs
akhileshs / gist:d19cc5ed5a88fc93607b
Created April 3, 2015 12:51
basic core.typed stuff
(ns typedclj.trial
(:require [clojure.core.typed :refer [check-ns ann ann-form cf ann-protocol ann-datatype] :as t]))
(ann my-inc [Number -> Number])
(defn my-inc [a] (inc a))
(ann collatz [Number -> Number])
(defn collatz [n]
(cond
scala> trait Plus[A] {
| def plus(a1: A, a2: A): A
| }
defined trait Plus
scala> def plus[A : Plus](a1: A, a2: A): A = implicitly[Plus[A]].plus(a1, a2)
plus: [A](a1: A, a2: A)(implicit evidence$1: Plus[A])A
scala> trait Functor[F[_]] { self =>
| def map[A, B](fa: F[A])(f: A => B): F[B]
| // lift f to F and apply on F[A]
| // ...
| }
defined trait Functor
@akhileshs
akhileshs / gist:2594fdaa879f1aeee23a
Created April 3, 2015 13:15
simulating a knight's move
scala> case class KnightPos(c: Int, r: Int)
defined class KnightPos
scala> :pa
// Entering paste mode (ctrl-D to finish)
case class KnightPos(c: Int, r: Int) {
def move: List[KnightPos] =
for {
KnightPos(c2, r2) <- List(KnightPos(c + 2, r - 1), KnightPos(c + 2, r + 1),
template <class A>
class Option {
bool isValid;
A value;
public:
Option() : isValid(false) {}
Option(A v) : isValid(true), value(v) {}
bool isValid() const { return isValid; }
A value() const { return value; }
template<class A>
class List {
Node *head;
public:
List(): head(nullptr) {}
List(A a, List<A> l)
: head(new Node(a, l))
{}
};
prodToSum :: (a, Either b c) -> Either (a, b) (a, c)
prodToSum (x, e) =
case e of
Left y -> Left (x, y)
Right z -> Right (x, z)
sumToProd :: Either (a, b) (a, c) -> (a, Either b c)
sumToProd e =
case e of
Left (x, y) -> (x, Left y)
user=> (defrecord TreeNode [val l r])
user.TreeNode
user=> (TreeNode. 5 nil nil)
#user.TreeNode{:val 5, :l nil, :r nil}
user=> (defn xconj [t v]
#_=> (cond
#_=> (nil? t) (TreeNode. v nil nil)
#_=> (< v (:val t)) (TreeNode. (:val t) (xconj (:l t) v) (:r t))
#_=> :else (TreeNode. (:val t) (:l t) (xconj (:r t) v))))
#'user/xconj