Tuesday, January 13, 2015

Anonymous functions, PAFs and map in clojure

Anonymous functions, PAFs and map in clojure

 
;; Two ways to write a partially applied functions in clojure (PAF)((fn [x] (str "Hi, " x)) "there.")
((partial str "Hi, ") "there.")
;; Define these PAFs(def addhi1 (fn [x] (str "Hi, " x)))
(def addhi2 (partial str "Hi, "))
;; Map these two PAFs to a list, results are the same(map addhi1 ["Newon", "Einstein"])
(map addhi2 ["Newon", "Einstein"])
;; Passing multiple args to a vector(defn addhi-map1 [& xs] (map addhi1 xs))
(defn addhi-map2 [& xs] (map addhi2 xs))
(addhi-map1 "Newton" "Einstein")
(addhi-map2 "Newton" "Einstein")

Saturday, January 10, 2015

Sieve of Eratosthenes implementaion in haskell

-- Sieve of Eratosthenes implementaion in haskell
sieve :: [Integer] -> [Integer]
-- If it starts with zero, simply filter out
sieve (0:xs) = sieve xs
-- If it's not marked as 0, return it, and sieve the rest.
-- The rest is the result of marking multiple of n
-- The marking process is nested, for example:
-- 3 : sieve (mark (mark [4..] 2 2) 3)
sieve (n:xs) = n : sieve (mark xs 1 n) where
mark :: [Integer] -> Integer -> Integer -> [Integer]
-- This is just counting, staring from 1, 2, 3..., once it reaches n, it's rest to 1.
-- For every n numbers, there is one marked with 0, to be sieved out.
mark (y:ys) k m
| k == m = 0 : (mark ys 1 m)
| otherwise = y : (mark ys (k+1) m)

primes :: [Integer]
primes = sieve [2..]

Circular Function calls in haskell.

-- Circular Function calls in haskell.
-- To understand how this works, imagine running `prime 11` in your mind
-- The key is lazy evaluation
prime :: Integer -> Bool
prime
| n < 1 = error "not a positive integer"
| n == 1 = False
| otherwise = ldp n == n where
-- ldp: least divising prime
ldp = ldpf primes
-- ldpf least divising prime from
ldpf (p:ps) m
| rem m p == 0 = p
| p^2 > m = m
| otherwise = ldpf ps m
primes = 2 : filter prime [3..]