Data.Tuple fst :: (a,b) -> a fst (x,_) = x snd :: (a,b) -> b snd (_,y) = y curry :: ((a, b) -> c) -> a -> b -> c curry f x y = f (x, y) uncurry :: (a -> b -> c) -> ((a, b) -> c) uncurry f p = f (fst p) (snd p) swap :: (a,b) -…
自定义 Lens 和 Isos -- Some of the examples in this chapter require a few GHC extensions: -- TemplateHaskell is needed for makeLenses; RankNTypes is needed for -- a few type signatures later on. {-# LANGUAGE TemplateHaskell, RankNTypes #-} import Control…
Category class Category cat where id :: cat a a (.) :: cat b c -> cat a b -> cat a c instance Category (->) where id = GHC.Base.id (.) = (GHC.Base..) (<<<) :: Category cat => cat b c -> cat a b -> cat a c (<<<) = (.) (&…
Data.Text.Read Prelude> :set -XOverloadedStrings Prelude> :m +Data.Text.Read Prelude Data.Text.Read> decimal "123" Right (123,"") Prelude Data.Text.Read> decimal "abc" Left "input does not start with a digit&…
Data.Typeable 利用 Data.Typeable,可以打印动态类型信息. class Typeable (a :: k) where typeRep# :: TypeRep a typeRep :: Typeable a => TypeRep a typeRep = typeRep# typeOf :: Typeable a => a -> TypeRep a typeOf _ = typeRep typeOf 函数可以返回某个值的类型信息. {-# LANGUAGE Der…
Data.Tree data Tree a = Node { rootLabel :: a, subForest :: Forest a } deriving (Eq, Read, Show) type Forest a = [Tree a] Data.Tree 是一种非空(存在根节点),可以有无限分支,每个节点均可有多路分支的Tree类型. Prelude Data.Tree> :t Node 1 Node 1 :: Num a => Forest a -> Tree a Prelud…
安装 free 包 $ cabal install free Installed free-5.0.2 Free Monad data Free f a = Pure a | Free (f (Free f a)) instance Functor f => Functor (Free f) where fmap f = go where go (Pure a) = Pure (f a) go (Free fa) = Free (go <$> fa) instance Functor f…
Comprehension Extensions 关于解析式的相关语言扩展. List and Comprehension Extensions 24 Days of GHC Extensions: List Comprehensions ParallelListComp Prelude> [(w,x,y,z) | ((w,x),(y,z)) <- zip [(w,x) | w <- [1..3], x <- [2..4]] [(y,z) | y <- [3..5], z &…
fix 函数 fix 是一个在 Data.Function 模块中定义的函数,它是对于递归的封装,可以用于定义不动点函数. fix :: (a -> a) -> a fix f = let x = f x in x fix 函数的定义使用了递归绑定,比较难以理解: fix f = let x = f x in x = let x = f x in f x = let x = f x in f (f x) = let x = f x in f (f (f x)) = let x = f x in…
Existentials(存在类型) Existentially quantified types(Existentially types,Existentials)是一种将一组类型归为一个类型的方式. 通常在使用 type, newtype, data 定义新类型的时候,出现在右边的类型参数必须出现在左边. 存在类型可以突破此限制. 实例 {-# LANGUAGE ExistentialQuantification #-} data ShowBox = forall s. Show s =>…
Enum class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] -- [n..] enumFromThen :: a -> a -> [a] -- [n,n'..] enumFromTo :: a -> a -> [a] -- [n..m] enumFromThenTo :: a -> a -> a…