Skip to content

Instantly share code, notes, and snippets.

@hyone
hyone / gist:904156
Created April 5, 2011 18:12
Is there any better way to validate new value is bigger than current value?
(def counter (agent 0))
(set-validator! counter (fn [n] (>= n @counter)))
@hyone
hyone / gist:917189
Created April 13, 2011 08:25
Primes by sieve of Eratosthenes (lazy evalution)
(defn nums [] (iterate inc 2))
(defn sieve [[p & xs]]
(remove #(= (rem % p) 0) xs))
(defn primes []
(map first (iterate sieve (nums))))
;; user> (take 20 (primes))
;; (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71)
@hyone
hyone / gist:926820
Created April 19, 2011 04:38
square root by newton raphson method
(ns newton-raphson
(:use
[clojure.contrib.math :only (abs)]
[clojure.contrib.seq :only (find-first)]))
(defn newton-raphson [improve, init]
(iterate improve init))
(defn within [eps xs]
@hyone
hyone / gist:997560
Created May 29, 2011 08:13
Accumulator by Java
interface Function1<A, R> {
R apply(A arg);
}
class Holder<T> {
public T value;
public Holder(T value) {
this.value = value;
}
}
@hyone
hyone / gist:997565
Created May 29, 2011 08:21
Accumulator by Clojure
(defn accumulator [n]
(let [i (atom n)]
(fn [x] (swap! i + x))))
;; user> (doseq [i (range 1 6)] (-> i (* 2) acc println))
;; 2
;; 6
;; 12
;; 20
@hyone
hyone / gist:997567
Created May 29, 2011 08:24
Accumulator by Scala
object Accumulator {
def accumulator(n: Int): Int => Int = {
var i = n
(x: Int) => { i += x; i }
}
def main(args: Array[String]) {
val acc = accumulator(0)
(1 to 5).foreach { i => println(acc(i * 2)) }
}
@hyone
hyone / gist:1032985
Created June 18, 2011 10:47
4clojure #53 - Longest continuous increasing subsequence
;; hyone's solution to Longest Increasing Sub-Seq
;; https://4clojure.com/problem/53
(fn longest-inc-seq [coll]
(reduce #(let [len-a (count %1)
len-b (count %2)]
(if (and (> len-b 1) (> len-b len-a)) %2 %1))
[]
(reductions
(fn [xs y]
@hyone
hyone / group-a-sequnce.clj
Created June 28, 2011 17:52
4clojure #63 - Group a Sequence
;; hyone's solution to Group a Sequence
;; https://4clojure.com/problem/63
(fn my-group-by [pred coll]
(reduce
(fn [dict m]
(let [ret (pred m)]
(assoc dict ret (conj (or (dict ret) []) m))))
{} coll))
@hyone
hyone / hyone-4clojure-solution65.clj
Created June 29, 2011 05:06 — forked from anonymous/hyone-4clojure-solution65.clj
4clojure #65 - Black Box Testing
;; hyone's solution to Black Box Testing
;; https://4clojure.com/problem/65
(defn seq-type [coll]
(let [base (empty coll)]
(cond
(= base {}) :map
(= base #{}) :set
(= base '()) (if (reversible? coll) :vector :list))))
@hyone
hyone / hyone-4clojure-solution69.clj
Created June 30, 2011 14:20 — forked from anonymous/hyone-4clojure-solution69.clj
4clojure #69 - Merge with a Function
;; hyone's solution to Merge with a Function
;; https://4clojure.com/problem/69
(fn my-merge-with [f & maps]
(reduce
(fn [a b]
(reduce
(fn [x [k v]]
(assoc x k (if (b k) (f v (b k)) v)))
b a))