所以,只是爲了好玩,我一直在Haskell中使用一個CountedList類型,使用Peano號碼 和smart constructors。Haskell計數列表類型
型號安全head
和tail
對我來說看起來很酷。
而且我想我已經達到了什麼,我知道該怎麼做
{-# LANGUAGE EmptyDataDecls #-}
module CountedList (
Zero, Succ, CountedList,
toList, ofList,
empty, cons, uncons,
head, tail,
fmap, map, foldl, foldr, filter
) where
import qualified List (foldr, foldl, filter)
import Prelude hiding (map, head, foldl, foldr, tail, filter)
data Zero
data Succ n
data CountedList n a = CL [a]
toList :: CountedList n a -> [a]
toList (CL as) = as
ofList :: [a] -> CountedList n a
ofList [] = empty
ofList (a:as) = cons a $ ofList as
empty :: CountedList Zero a
empty = CL []
cons :: a -> CountedList n a -> CountedList (Succ n) a
cons a = CL . (a:) . toList
uncons :: CountedList (Succ n) a -> (a, CountedList n a)
uncons (CL (a:as)) = (a, CL as)
head :: CountedList (Succ n) a -> a
head = fst . uncons
tail :: CountedList (Succ n) a -> CountedList n a
tail = snd . uncons
instance Functor (CountedList n) where
fmap f = CL . fmap f . toList
map :: (a -> b) -> CountedList n a -> CountedList n b
map = fmap
foldl :: (a -> b -> a) -> a -> CountedList n b -> a
foldl f a = List.foldl f a . toList
foldr :: (a -> b -> b) -> b -> CountedList n a -> b
foldr f b = List.foldr f b . toList
filter :: (a -> Bool) -> CountedList n a -> CountedList m a
filter p = ofList . List.filter p . toList
極限(對不起任何抄寫錯誤 - 機器我最初寫這個的瓦特/我Haskell編譯當前已關閉) 。
我所做的大部分工作都是在沒有問題的情況下編譯的,但我遇到了ofList
和filter
的問題。我想我理解爲什麼 - 當我說ofList :: [a] -> CountedList n a
時,我說的是ofList :: forall n . [a] -> CountedList n a
- 創建的列表可以是任何需要的計數類型。我想寫的是相當於僞類型ofList :: exists n . [a] -> CountedList n a
,但我不知道如何。
有沒有一種解決方法可以讓我編寫ofList
和filter
函數,就像我想象的一樣,還是我已經達到了可以用這個函數完成的極限?我有一個感覺,那就是我錯過了existential types。
我不知道爲什麼有人會downvote這個題。我保持平衡。 – 2010-01-14 16:00:51
看起來像有人點擊downvote錯誤並修復它:目前沒有downvote。 – JaakkoK 2010-01-14 16:02:45
事實上,我點擊了我手機上的錯誤按鈕,然後失去了網絡連接。我希望堆棧溢出將在不久的將來得到一個移動樣式表(帶有一些更大的箭頭):-) – 2010-01-14 16:12:57