这个想法是实现“惰性”长度函数来将列表长度与 Int 进行比较,而不计算整个长度。
{-# LANGUAGE DeriveFunctor
, TypeFamilies
, FlexibleInstances #-}
import Data.Functor.Foldable
type instance Base Int = Maybe
现在我们可以有可折叠/不可折叠
instance Foldable Int where
project 0 = Nothing
project x = Just (x-1)
instance Unfoldable Int where
embed Nothing = 0
embed (Just x) = x+1
我想将 [a] 转换为 Base Int Int:
leng :: [a] -> Base Int Int
leng = ana phi where
phi :: [a] -> Base Int [a]
phi [] = Nothing
phi (_:t) = Just t
但这不起作用。它抱怨 [a] -> Base (Maybe Int) [a] 应该是 phi 的类型。我不明白为什么。
如果可行,那么我可以比较:
gt = curry $ hylo psi phi where
phi (Just _, Nothing) = Left True
phi (Nothing, _) = Left False
phi (Just t, Just n) = Right (t, n)
psi (Left t) = t
psi (Right t) = t
main = print $ (leng [1..]) `gt` (ana project 4)
冷有什么问题?