/
NonEmpty.purs
74 lines (59 loc) · 2.14 KB
/
NonEmpty.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
module Data.List.Lazy.NonEmpty
( module Data.List.Lazy.Types
, toUnfoldable
, fromFoldable
, fromList
, toList
, singleton
, head
, tail
, init
, uncons
, length
, concatMap
, appendFoldable
) where
import Prelude
import Data.Foldable (class Foldable)
import Data.Lazy (force, defer)
import Data.List.Lazy ((:))
import Data.List.Lazy as L
import Data.List.Lazy.Types (NonEmptyList(..))
import Data.Maybe (Maybe(..), maybe, fromMaybe)
import Data.NonEmpty ((:|))
import Data.Tuple (Tuple(..))
import Data.Unfoldable (class Unfoldable, unfoldr)
toUnfoldable :: forall f. Unfoldable f => NonEmptyList ~> f
toUnfoldable =
unfoldr (\xs -> (\rec -> Tuple rec.head rec.tail) <$> L.uncons xs) <<< toList
fromFoldable :: forall f a. Foldable f => f a -> Maybe (NonEmptyList a)
fromFoldable = fromList <<< L.fromFoldable
fromList :: forall a. L.List a -> Maybe (NonEmptyList a)
fromList l =
case L.step l of
L.Nil -> Nothing
L.Cons x xs -> Just (NonEmptyList (defer \_ -> x :| xs))
toList :: NonEmptyList ~> L.List
toList (NonEmptyList nel) = case force nel of x :| xs -> x : xs
singleton :: forall a. a -> NonEmptyList a
singleton = pure
head :: forall a. NonEmptyList a -> a
head (NonEmptyList nel) = case force nel of x :| _ -> x
last :: forall a. NonEmptyList a -> a
last (NonEmptyList nel) = case force nel of x :| xs -> fromMaybe x (L.last xs)
tail :: forall a. NonEmptyList a -> L.List a
tail (NonEmptyList nel) = case force nel of _ :| xs -> xs
init :: forall a. NonEmptyList a -> L.List a
init (NonEmptyList nel) =
case force nel
of x :| xs ->
maybe L.nil (x : _) (L.init xs)
uncons :: forall a. NonEmptyList a -> { head :: a, tail :: L.List a }
uncons (NonEmptyList nel) = case force nel of x :| xs -> { head: x, tail: xs }
length :: forall a. NonEmptyList a -> Int
length (NonEmptyList nel) = case force nel of x :| xs -> 1 + L.length xs
concatMap :: forall a b. (a -> NonEmptyList b) -> NonEmptyList a -> NonEmptyList b
concatMap = flip bind
appendFoldable :: forall t a. Foldable t => NonEmptyList a -> t a -> NonEmptyList a
appendFoldable nel ys =
NonEmptyList (defer \_ -> head nel :| tail nel <> L.fromFoldable ys)