Skip to content

Instantly share code, notes, and snippets.

View schar's full-sized avatar
💭
🦧

Simon Charlow schar

💭
🦧
View GitHub Profile
@schar
schar / HistoFib.hs
Last active November 4, 2022 19:08
module Intro where
import Control.Arrow ((&&&))
newtype Term f =
In { out :: f (Term f) }
type Algebra f a = f a -> a
cata :: (Functor f) => Algebra f a -> Term f -> a
@schar
schar / PopLens.hs
Last active October 24, 2022 17:09
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TupleSections #-}
module PopLens where
data IStore a b t = IStore a (b -> t)
deriving (Functor)
type Lens s t a b = s -> IStore a b t
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.State.Lazy
import Data.Map hiding (map, splitAt)
import Prelude hiding (lookup)
memoize2 f p@(x, _) = do -- only uses 1st arg as key
v <- gets $ lookup x
case v of
Just y -> return y
@schar
schar / Memo.hs
Created June 11, 2022 00:26
Haskell memoization monadically
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.Identity
import Control.Monad.State.Lazy
import Data.Map
import Prelude hiding (lookup)
memoize :: (MonadState (Map k a) m, Ord k) =>
(k -> m a) -> k -> m a
memoize f x = do
@schar
schar / Ex.hs
Created December 12, 2021 03:20
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
data Ex = forall a. Ex a
type State i o a = i -> (a, o)
-- enforce independence of types i and a:
newtype Filt a = Filt { unFilt :: forall i. i -> (a, Ex) }
@schar
schar / CKY.hs
Last active March 23, 2022 14:37
10-lines for CKY parsing in Haskell
mkChart :: (Eq cat, Eq term) =>
CFG cat term -> [term] -> [((Int, Int), [cat])]
mkChart g xs = helper (0,1) [] where
helper p@(i,j) tab
| j>length xs = tab
| i<0 = helper (j,j+1) tab
| i==j-1 = helper (i-1,j) $
(p, [n | n:-t <- g, t==xs!!(j-1)]):tab
| otherwise = helper (i-1,j) $
(p, [n | n:>(l,r) <- g, k <- [i+1..j-1],
@schar
schar / CFParse.hs
Last active March 23, 2022 14:33
Incredibly simple but extremely non-performant CFG parsing
import Data.Tree
splitsPlus :: [a] -> [([a], [a])]
splitsPlus u = [splitAt i u | i <- [1..length u - 1]]
data Rule n x = n :- x | n :< (n, n)
deriving (Eq, Show)
parse
:: (Eq cat, Eq term) =>
{-# LANGUAGE OverloadedStrings #-}
module Re (
Re,
(<>), (<+>), star, zero, one, neg,
nullable, derive, mkDfa, minimize,
anyc, alpha, lower, upper, digit
) where
import Data.Char
{-# LANGUAGE OverloadedStrings #-}
module Regexp (
Regexp,
(<+>), (<>), star, zero,
match, anyc
) where
import Data.Char
import GHC.Exts (IsString (..))
module Markov where
import qualified Control.Monad.Random as R
import qualified Data.Map as M
import Utils
type Hist = [String] -- prior context as list of words
type Next = String
type Ngrams = [(Hist, Next)]