[<<][haskell][>>][..]
Sun Aug 30 21:18:57 CEST 2015

_not_ using reader monad

Explicit reader is sometimes more clear.

data Trie a b = Node [(a, Trie a b)]
              | Leaf b deriving (Eq, Show)


foldrPairs f i a = runReader (fld i a) [] where
  fld i (Leaf a) = do
    ts <- ask
    return $ f (ts, a) i
  fld i (Node []) =
    return i
  fld i (Node ((t,a):r)) = do
    i' <- fld i (Node r)
    local (++[t]) (fld i' a)

foldrPairs f i a = fld [] i a where
  fld ts i (Leaf a) = f (ts, a) i
  fld _  i (Node []) = i
  fld ts i (Node ((t,a):r)) = fld (t:ts) (fld ts i $ Node r) a


or

foldrPairs f i a = fld [] i a where
  fld ts i (Leaf a) = f (ts, a) i
  fld ts i (Node ((t,a):r)) = i'' where 
    i'  = fld ts i $ Node r  -- inner
    i'' = fld (ts++[t]) i' a -- outer
  fld _  i (Node []) = i

or using foldr

foldrPairs f i a = fld [] i a where
  fld ts i (Leaf a) = f (ts, a) i
  fld ts i (Node tas) = foldr f' i tas where
    f' (t,a) i = fld (ts++[t]) i a




[Reply][About]
[<<][haskell][>>][..]