Foldr lists

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{-# LANGUAGE RankNTypes #-}

module Main 
where

--- http://stackoverflow.com/questions/13346200/type-safe-difference-lists

newtype F a = F { runF :: forall r. r -> (a -> r -> r) -> r }

empty = F const    -- (\r g->r)
singleton x = F (\r g-> g x r)

fromList []     = empty 
fromList (x:xs) = F (\r g-> g x $ runF (fromList xs) r g)

fromList' []     = empty 
fromList' (x:xs) = F (\r g-> g x $ runF (fromList' xs) (g x r) g)

toList a = runF a [] (:)
toSum a = runF a 0 (+)

append a b = F (\r g-> runF a (runF b r g) g) 
endapp a b = F (\r g-> runF b (runF a r g) g)