天天看點

Haskell語言學習筆記(70)NonEmpty

NonEmpty(非空清單)

infixr  :|

data NonEmpty a = a :| [a]
  deriving (Eq, Ord)

instance Functor NonEmpty where
  fmap f ~(a :| as) = f a :| fmap f as
  b <$ ~(_ :| as)   = b   :| (b <$ as)

instance Applicative NonEmpty where
  pure a = a :| []
  (<*>) = ap
  liftA2 = liftM2

instance Monad NonEmpty where
  ~(a :| as) >>= f = b :| (bs ++ bs')
    where b :| bs = f a
          bs' = as >>= toList . f
          toList ~(c :| cs) = c : cs
           

NonEmpty是一個非空的list類型,支援大多數 list 類型的操作。

Prelude> import Data.List.NonEmpty as NE
Prelude NE> a = 5 :| []
Prelude NE> :t a
a :: Num a => NonEmpty a
Prelude NE> NE.head a
5
Prelude NE> NE.tail a
[]
Prelude NE> b = 6 <| a
Prelude NE> b
6 :| [5]
Prelude NE> NE.map (+2) b
8 :| [7]
Prelude NE> 3 <$ b
3 :| [3]
Prelude NE> fromList [1,2,3]
1 :| [2,3]
Prelude NE> toList it
[1,2,3]
           
  • :| 是構造器,a : [a] 得到清單,而 a :| [a] 得到 NonEmpty清單。
  • <| 在 NonEmpty清單前端添加元素,相當于 [] 的 : 。
  • fromList toList 用于實作 NonEmpty 與 [] 之間的轉換