Haskell替代类和守卫的空功能

时间:2017-07-11 22:06:18

标签: haskell functional-programming

假设我有以下ADT,

data Properties a = Property String a
    deriving (Show,Eq)

我为它做了以下实例,

instance Functor Properties where
  fmap f (Property name prop) = Property name (f prop)
--
instance Applicative (Properties) where
  pure a = Property "" a
  (Property _ f) <*> p = fmap f p

instance Monad (Properties) where
  return a = Property "" a
  (Property name prop) >>= f = (f prop)

到目前为止一切顺利。让我们看看到目前为止我们能做些什么,

pColors = Property "Color" ["Blue", "Red", "White"]
pNationality = Property "Nationality" ["Italian", "Norwegian", "Spanish"]

answers = do
  color <- fmap permutations pColors
  nation <- fmap permutations pNationality
  return $ zip color nation

给出,

*Main> answers
Property "" [(["Blue","Red","White"],["Italian","Norwegian","Spanish"]),(["Red","Blue","White"],["Norwegian","Italian","Spanish"]),(["White","Red","Blue"],["Spanish","Norwegian","Italian"]),(["Red","White","Blue"],["Norwegian","Spanish","Italian"]),(["White","Blue","Red"],["Spanish","Italian","Norwegian"]),(["Blue","White","Red"],["Italian","Spanish","Norwegian"])]

所以fmap和monadic绑定按预期工作。现在我想使用guard中的alternative函数。基本上我想根据一些谓词修剪pColorspNationality。所以我试着定义,

instance Alternative (Properties) where
  empty = Property "" []

但是这给了我一个错误,我认为(如果我错了请纠正我),因为Haskell正在将[]解释为与a不同。但我认为a可以是任何东西而[]是任何东西之一,那么问题是什么?

1 个答案:

答案 0 :(得分:4)

  

但我认为a可以是任何内容而[]是其中之一,那么问题是什么?

并不是a可以是任何东西,但a必须能够成为任何东西。也就是说,如果用户写入x :: Property [a]; x = empty,则必须允许,但也必须允许x :: Property Int; x = empty。你的定义只允许前者,所以它是不正确的。

除非您产生错误(例如empty)或将Property的定义更改为empty = Property "" undefined,否则无法为Property类型定义有效的 public Container getContentPane() { return getRootPane().getContentPane(); } 为空属性添加一个案例。