Skip to content

Instantly share code, notes, and snippets.

View onlyshk's full-sized avatar

Kuleshov Alexander onlyshk

View GitHub Profile
@onlyshk
onlyshk / gist:1441848
Created December 7, 2011 07:24
list lifting
plus :: [Int] -> [Int] -> [Int]
plus = liftM2 (+)
-- plus [1,2,3] [3,6,9] ---> [4,7,10, 5,8,11, 6,9,12]
-- plus [1..] [] ---> _|_ (i.e., keeps on calculating forever)
-- plus [] [1..] ---> []
@onlyshk
onlyshk / gist:1441842
Created December 7, 2011 07:21
Monad lifting
return :: (Monad m) => a -> m a
liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r
liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
@onlyshk
onlyshk / gist:1441804
Created December 7, 2011 07:04
Lifting functions more than 1 parameter
lift0 :: a -> Pair a
lift0 x = Pair x x
lift2 :: (a -> b -> r) -> (Pair a -> Pair b -> Pair r)
lift2 f (Pair x1 x2) (Pair y1 y2) = Pair (f x1 y1) (f x2 y2)
plus :: Pair Int -> Pair Int -> Pair Int
plus = lift2 (+)
-- plus (Pair 1 2) (Pair 3 4) ---> Pair 4 6
@onlyshk
onlyshk / gist:1441795
Created December 7, 2011 06:59
Function lifting
lift :: (a -> b) -> Pair a -> Pair b
lift = fmap
plus2 :: Pair Int -> Pair Int
plus2 = lift (+2)
-- plus2 (Pair 2 3) ---> Pair 4 5
@onlyshk
onlyshk / gist:1441777
Created December 7, 2011 06:54
data Pair
data Pair a = Pair a a deriving Show
instance Functor Pair where
fmap f (Pair x y) = Pair (f x) (f y)
test() ->
Num = 232,
List = [{1, 0, 200}, {2, 200, 600}],
[{Num2, _, _}] = lists:filter(fun(X) ->
{Number, X1, X2} = X,
(Num >= X1) and (Num =< X2)
end,
List),
Num2.
@onlyshk
onlyshk / gist:1338842
Created November 4, 2011 07:20
Foldable
class Foldable t where
foldr :: (a -> b -> b) -> b -> [a] -> [b]
foldMap :: (Monoid m, Foldable t) => (a -> m) -> t a -> m
@onlyshk
onlyshk / gist:1338838
Created November 4, 2011 07:13
foldl and foldr by step
-- Computing steps:
-- 1) 1 + foldr ( (+) 0 [2,3,4,5])
-- 2) 1 + 2 + foldr ( (+) 0 [3,4,5])
-- 3) 1 + 2 + 3 + foldr ( (+) 0 [4,5])
-- 4) 1 + 2 + 3 + 4 + foldr ((+) 0 [5])
-- 5) 1 + 2 + 3 + 4 + 5 + foldr ((+) 0 [])
-- 6) 1 + 2 + 3 + 4 + 5 + 0
foldr (+) 0 [1,2,3,4,5]
@onlyshk
onlyshk / gist:1338805
Created November 4, 2011 06:47
foldl and foldr
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl _ z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
@onlyshk
onlyshk / gist:1338791
Created November 4, 2011 06:36
Map and filter example
map (\x -> x * 2) [1,2,3,4,5]
-- Result :
[2,4,6,8,10]
filter even [1,2,3,4,5]
-- Result :
[2,4]