这个想法是实现“懒惰”长度函数来将列表长度与Int进行比较而不计算整个长度。
{-# LANGUAGE DeriveFunctor
, TypeFamilies
, FlexibleInstances #-}
import Data.Functor.Foldable
type instance Base Int = Maybe
现在我们可以使用Foldable / Unfoldable
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)
leng有什么问题?
答案 0 :(得分:3)
ana
的类型为(a -> Base t a) -> a -> t
。请注意,它返回普通t
而不是Base t t
。所以leng
的正确类型是
leng :: [a] -> Int
答案 1 :(得分:3)
感谢您指出类型错误。获得正确的类型澄清了这个想法:)
{-# LANGUAGE DeriveFunctor
, TypeFamilies
, FlexibleInstances #-}
import Data.Functor.Foldable
type instance Base ([a], Int) = Either Bool
instance Foldable ([a], Int) where
project ([], _) = Left False
project (_, 0) = Left True
project ((h:t), n) = Right (t, n-1)
longerThan :: [a] -> Int -> Bool
longerThan = curry $ cata $ either id id
main = print $ [1..] `longerThan` 4
满意?让我们扩展这个以说明为什么我真正开始这一切:
{-# LANGUAGE DeriveFunctor
, TypeFamilies
, FlexibleInstances
, FlexibleContexts
, UndecidableInstances #-}
import Data.Functor.Foldable
data Zip a b x = Z (Base a (Base b x))
instance (Functor (Base a), Functor (Base b)) => Functor (Zip a b) where
fmap f (Z a) = Z $ fmap (\x -> fmap f x) a
type instance Base (a, b) = Zip a b
获得提示?我们可以同时递归两种结构!
instance (Foldable a, Foldable b) => Foldable (a, b) where
project (a, b) = Z $ fmap (\x -> fmap (\y -> (x,y)) $ project b) $ project a
演示:引入Base Int,并检查列表的长度是否大于给定的Int。
type instance Base Int = Maybe
instance Foldable Int where
project 0 = Nothing
project x = Just $ x-1
-- lt and gt are the same;
-- just showing off with the order of arguments, so you can appreciate Zip
lt :: Int -> [a] -> Bool
lt = curry $ cata phi where
phi (Z Nothing) = True
phi (Z (Just Nil)) = False
phi (Z (Just (Cons _ t))) = t
gt :: [a] -> Int -> Bool
gt = curry $ cata phi where
phi (Z (Cons _ Nothing)) = True
phi (Z Nil) = False
phi (Z (Cons _ (Just t))) = t
main = print [[1..] `gt` 4, 4 `lt` [1..]]
答案 2 :(得分:2)
这可能会破坏使用类型系列执行此操作的目的,但如果您只是想要一个'懒惰的比较列表长度与int'功能,您可以直接编写它:
cmp :: [a] -> Int -> Ordering
cmp [] n = compare 0 n
cmp (_:xs) n = if n <= 0 then GT else cmp xs (n - 1)
答案 3 :(得分:0)
@PaulVisschers正在实现的功能,这确实是做你想要的最简单的方法之一,如果出于某种原因想要用Foldable
进行练习,可以用一个变形实现。 / p>
import Data.Functor.Foldable
cmp :: [a] -> Int -> Ordering
cmp = cata psi
psi :: Base [a] (Int -> Ordering) -> Int -> Ordering
psi Nil n = compare 0 n
psi (Cons h t) n = if n <= 0 then GT else t (n-1)