summaryrefslogtreecommitdiff
path: root/testsuite/tests/cpranal/should_compile/T18401.hs
blob: c850d9a7e0398562a99568e3733ed6f0f3cfb88e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{-# OPTIONS_GHC -O2 -fforce-recomp -dno-typeable-binds #-}

module T18401 where

-- | A safe version of `init`.
-- @safeInit [] = Nothing@
-- @safeInit xs = Just $ init xs@
safeInit :: [a] -> Maybe [a]
safeInit xs = case si xs of
  (False, _) -> Nothing
  (_, ys) -> Just ys

si :: [a] -> (Bool, [a])
si xs0 = foldr go stop xs0 Nothing
  where
    stop Nothing = (False, [])
    stop _ = (True, [])
    go x r Nothing = (True, snd (r (Just x)))
    go x r (Just p) = (True, p : snd (r (Just x)))