重新定义列表monad实例



我想为列表monad提供我自己的实例。不幸的是,以下内容在编译时会导致重复的实例声明错误。

myReturn :: a -> [a]
myBind :: [a] -> (a -> [b]) -> [b]
instance Monad [] where
    return = myReturn
    (>>=) = myBind

从文档中看,导入时似乎不可能隐藏实例声明,而且由于list monad实例已经在序言中声明,我想我也无法摆脱导入本身。

我想,也许我至少可以重新绑定(>>=)return,这样我就可以使用我自己的实现来使用do块,因为do块应该只是(>>=)(>>)应用程序的语法糖。

let
    return = myReturn
    (>>=) = myBind
in
    do
        item1 <- list1
        item2 <- list2
        return (item1, item2)

不幸的是,do块似乎从其他地方获得了它们的(>>=),因为它仍然使用默认列表monad实例的(>>=)

有没有什么方法可以让我的(>>=)return实现成为列表monad的实例,或者至少有一种方法可以将它们与do块一起使用?

您不能为列表定义另一个Monad实例,在某些情况下,您可以定义一个newtype来解决这个问题,但您必须手动将所有列表函数提升到newtype才能使用它们。

要在do块中只使用您自己的(>>=)return,您可以使用GHC:的语言扩展

{-# LANGUAGE NoImplicitPrelude #-}
module ListMon where
import Prelude hiding ((>>=), return)
(>>=) :: [a] -> (a -> [b]) -> [b]
xs >>= foo = case xs of
               [] -> [undefined]
               [x] -> foo x ++ foo x
               ys -> take 10 $ concatMap foo $ take 5 ys
return :: a -> [a]
return x = [x,x,x]
someList :: [Int]
someList = do
    k <- [1 .. 4]
    h <- [2 .. 3]
    return (k + 12*h)

导致

$ ghci ListMon
{- snip loading messages -}
[1 of 1] Compiling ListMon          ( ListMon.hs, interpreted )
Ok, modules loaded:
*ListMon> someList 
[25,25,25,37,37,37,26,26,26,38,38,38,27,27,27,39,39,39,28,28,28,40,40,40]

对于NoImplicitPrelude,do表示法的去格化使用范围内的(>>=)return

您可以将列表包装在一个新类型的中

newtype MyList a = MyList { unMyList :: [a] }

并声明此包装类型的实例

instance Monad MyList where
    return = MyList . myReturn
    (MyList m) >>= f = MyList . myBind m f

现在,只需将列表包装在newtype包装器MyList中(newtype只是语法糖,因此在编译时会被删除)。

最新更新