Skip to content

Instantly share code, notes, and snippets.

@lambda-fairy
Last active November 22, 2016 05:56
Show Gist options
  • Select an option

  • Save lambda-fairy/5ccc8db995c6ed0cc282 to your computer and use it in GitHub Desktop.

Select an option

Save lambda-fairy/5ccc8db995c6ed0cc282 to your computer and use it in GitHub Desktop.
Hacking number literals
instance (Integral a, Num b) => Num (a -> b) where
fromInteger x = \y -> fromInteger (x * 1000 + toInteger y)
a, b :: Integer
a = 12 345
b = 1 048 576
{-# LANGUAGE TypeFamilies #-}
class Thing t where
type Inner t :: *
thing :: [Inner t] -> t
instance (Thing r, a ~ Inner r) => Thing (a -> r) where
type Inner (a -> r) = a
thing xs = thing . (: xs)
instance Thing [a] where
type Inner [a] = a
thing xs = reverse xs
instance (Thing r, a ~ Inner r, Num a) => Num (a -> r) where
fromInteger x = thing [fromInteger x]
instance Num a => Num [a] where
fromInteger x = [fromInteger x]
a, b :: [Integer]
a = 1 2 3 4 5
b = 42
{-# LANGUAGE TypeFamilies #-}
import Data.List (mapAccumL)
import Data.Maybe (maybeToList)
class Thing t where
type Inner t :: *
thing :: [Inner t] -> t
instance (Thing r, a ~ Inner r) => Thing (a -> r) where
type Inner (a -> r) = a
thing xs = thing . (: xs)
instance Thing [a] where
type Inner [a] = a
thing xs = reverse xs
instance (Thing r, a ~ Inner r, Num a) => Num (a -> r) where
fromInteger x = thing [fromInteger x]
instance Num a => Num [a] where
fromInteger x = [fromInteger x]
list :: Num a => [[a]] -> [a]
list xss = case mapAccumL slurp Nothing xss of
(y, xss') -> concat xss' ++ maybeToList y
where
slurp y [] = (y, [])
slurp Nothing xs = splitLast xs
slurp (Just y) (x:xs) = splitLast $ (y * 1000 + x) : xs
splitLast :: [a] -> (Maybe a, [a])
splitLast xs = case xs of
[] -> (Nothing, [])
x : [] -> (Just x, [])
x : xs' ->
let (b, as) = splitLast xs'
in (b, x:as)
test :: [Integer]
test = list [1 4,008 2 3 1,048,576 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment