Skip to content

Instantly share code, notes, and snippets.

-- Captain Crunch fun: serialization in Haskell using cereal ("serial, cereal... get it?")
-- Install: cabal install cereal
-- serialization
main = do
let msg = "hello cereal!"
cerealized = encode msg
writeFile "myFile" cerealized
-- Given a timestamp from a JSON API call
-- Need to convert to Epoch
import Control.Applicative ((<$>))
import Control.Monad (liftM)
import Data.Time
import Data.Time.Clock.POSIX
import System.Locale
main = do
-- the below will fail
data Type1 = Type1 { title :: String, another :: Integer }
data Type2 = Type2 { title :: String, random :: Integer }
-- with an error of "Multiple declarations of 'title'" or something along the lines
-- Thread on Stackoverflow: http://stackoverflow.com/questions/5367167/haskell-record-syntax
-- My simple cheap workaround was to seperate them into different sub-module files (obviously not scalable)
-- Thanks to Chris Forno (http://jekor.com/) who directed me to possible ways (and new brain food!)
data ConnectionTest = ConnectionTest { ctVersion :: String, ctResult :: String }
deriving (Show)
instance ToJSON ConnectionTest where
toJSON (ConnectionTest versionV resultV) = object [ "ctVersion" .= versionV,
"ctResult" .= resultV ]
instance FromJSON ConnectionTest where
parseJSON (Object v) = ConnectionTest <$>
v .: "version" <*>
@qoelet
qoelet / 2to3.hs
Last active December 23, 2015 19:49
-- from a pair to a triple.
-- a lambda for my newborn son.
((\z (x,y) -> (x, y, z)) "Isaac" ((\x y -> (x,y)) "Kenny" "Audrey"))
-- ("Kenny","Audrey","Isaac")
-- I finally got sick of reading books on Maybe and IO monads!
-- I spyed beyond that there must be mooarrr!
import Control.Monad.Identity
agent :: (Num a) => a -> Identity a
agent n = do
return n >>= (\n -> Identity (n * 2))
main :: IO ()
sinusoid :: [Double] -> Double -> Double -> Double -> [Double]
sinusoid [] _ _ _ = []
sinusoid (n:ns) amp ang_freq phase = amp * (cos (ang_freq * n + phase)) : sinusoid ns amp ang_freq phase
import Data.List
import Control.Applicative
main :: IO ()
main = do
let tt = [True, True]
ff = [False, False]
tf = head perms_tf
ft = reverse (head perms_tf)
perms_tf = permutations [True, False]
@qoelet
qoelet / goto.hs
Created September 14, 2013 08:38
-- Another day in #haskell
-- (fix $ \goto x -> case x of Nothing -> "hello"; Just _ -> goto Nothing) (Just ())
-- lambdabot: "hello"
import Data.Function (fix)
goto :: Maybe t -> [Char]
goto t = (fix (\goto x -> case x of Nothing -> "hello"; Just _ -> goto Nothing)) t
-- ghci> goto (Just 5)
-- determine if function f is even or odd
even_f :: (Eq a,Num a) => (a -> a) -> a -> Bool
even_f f x | f x == f (-x) = True
| otherwise = False
odd_f :: (Eq a, Num a) => (a -> a) -> a -> Bool
odd_f f x | (-(f x)) == f (-x) = True
| otherwise = False