Bar2 class Foo f where foo :: f a -> Either [String] a instance Foo Bar where foo (Bar1 x) = ...

问题描述 投票:1回答:1
I ended up changing my class to have the fully applied input and output type. It's a little bit clunky but it works.

data Bar a = Bar1 a | Bar2

class Foo f where
  foo :: f a -> Either [String] a

instance Foo Bar where
  foo (Bar1 x) = Right x
  foo Bar2 = Left ["is Bar2"]

我不确定这是否可能。我有一个类似下面的类。Foo f现在,我想能够定义一个实例,给定一个实现为 Foo [f] 实施

.

data Bar a = Bar1 a | Bar2

class Foo f where
  foo :: f a -> Either [String] a

instance Foo Bar where
  foo (Bar1 x) = Right x
  foo Bar2 = Left ["is Bar2"]

instance Foo f => Foo [f] where
  foo as = foldr reducer (Right []) (foo <$> as)
    where
      reducer (Right n) (Right xs) = Right $ n:xs
      reducer (Left xs) (Right _)  = Left xs
      reducer (Right _) (Left xs)  = Left xs
      reducer (Left xs) (Left ys)  = Left $ xs ++ ys

所以类似这样。[f] a列表实例只是积累所有的左数,如果没有左数,它就会删除外列表,并把它移到右边(能不能写得简单点? )。这样的实例不进行类型检查,因为类型不是 [f a] 不过 foo :: [f a] -> Either [String] [a]

. 我期望的类型是

type ApplyList (f :: Type -> Type) (a :: Type) = [f a]

instance Foo f => Foo (ApplyList f) where
...

我试着写了一个类型,这个类型对我来说是这样的。

但这是行不通的,因为我想类型不支持咖喱。

有什么办法可以正确的写出这个吗?

任何帮助都是感激的!
haskell typeclass higher-kinded-types
1个回答
2
投票

我不确定这是否可能。我有一个类似下面的类:数据Bar a = Bar1 a。

© www.soinside.com 2019 - 2024. All rights reserved.