鉴于类型类
class Dictionary w where
insert :: String -> String -> w -> w
remove :: String -> w -> w
lookUp :: String -> w -> String
Run Code Online (Sandbox Code Playgroud)
我写不出来
instance Dictionary [(String,String)] where
insert key value dic = (key,value) : remove key dic
remove key dic = filter (\entry -> (fst entry) /= key) dic
lookUp key [] = "not found"
lookUp key ((k,v):xs) | k == key = v
| otherwise = lookUp key xs
Run Code Online (Sandbox Code Playgroud)
因为
Illegal instance declaration …Run Code Online (Sandbox Code Playgroud) 作为练习,我在Haskell中实现了一个'cons'操作,它从任意类型的两个值形成一对.实现所需的数据类型非常简单:
data Nil = Nil deriving (Eq)
data Pair a b = Cons a b deriving (Eq)
car (Cons x _) = x
cdr (Cons _ y) = y
caar = car . car
cdar = cdr . car
cadr = car . cdr
cddr = cdr . cdr
*Main> cddr (Cons 55 (Cons (1,2,3,4) "hello, world!"))
"hello, world!"
*Main>
Run Code Online (Sandbox Code Playgroud)
但是受到这个主题的启发,我想让结果对打印出来像Scheme列表一样 - 包括臭名昭着的"不正确的列表"(1 2 3 .4).我的实施(见下文)适用于Char的:
*Main> Cons 'a' (Cons 'b' (Cons 'c' Nil))
('a' 'b' 'c')
*Main> …Run Code Online (Sandbox Code Playgroud) crypto-api包中有一个Crypto.Random API,用于指定"伪随机数生成器"的含义.
我使用System.Random的RandomGen类的实例,即StdGen实现了这个API:
instance CryptoRandomGen StdGen where
newGen bs = Right $ mkStdGen $ shift e1 24 + shift e2 16 + shift e3 8 + e4
where (e1 : e2 : e3 : e4 : _) = Prelude.map fromIntegral $ unpack bs
genSeedLength = Tagged 4
genBytes n g = Right $ genBytesHelper n empty g
where genBytesHelper 0 partial gen = (partial, gen)
genBytesHelper n partial gen = genBytesHelper (n-1) (partial `snoc` nextitem) newgen
where (nextitem, newgen) = …Run Code Online (Sandbox Code Playgroud)