Haskell:'没有实例'来自于对Regex库的简单使用

时间:2010-03-23 17:26:37

标签: haskell typeclass

根据this question的(已接受)回答,我期待以下工作:

Prelude Text.Regex.Posix Text.Regex.Base.RegexLike Text.Regex.Posix.String> makeRegex ".*"

makeRegex是具有预定义选项的makeRegexOpts的快捷方式)

然而,它没有:

<interactive>:1:0:
    No instance for (RegexMaker regex compOpt execOpt [Char])
      arising from a use of `makeRegex' at <interactive>:1:0-13
    Possible fix:
      add an instance declaration for
      (RegexMaker regex compOpt execOpt [Char])
    In the expression: makeRegex ".*"
    In the definition of `it': it = makeRegex ".*"
Prelude Text.Regex.Posix Text.Regex.Base.RegexLike Text.Regex.Posix.String> make
Regex ".*"::Regex

<interactive>:1:0:
    No instance for (RegexMaker Regex compOpt execOpt [Char])
      arising from a use of `makeRegex' at <interactive>:1:0-13
    Possible fix:
      add an instance declaration for
      (RegexMaker Regex compOpt execOpt [Char])
    In the expression: makeRegex ".*" :: Regex
    In the definition of `it': it = makeRegex ".*" :: Regex

我真的不明白为什么。

修改

Windows上的Haskell平台2009.02.02(GHC 6.10.4)

EDIT2

Prelude Text.Regex.Base.RegexLike Text.Regex.Posix.String> :i RegexMaker
class (RegexOptions regex compOpt execOpt) => RegexMaker regex compOpt execOpt source | regex -> compOpt execOpt, compOpt -> regex execOpt, execOpt -> regex compOpt where
  makeRegex :: source -> regex
  makeRegexOpts :: compOpt -> execOpt -> source -> regex
  makeRegexM :: (Monad m) => source -> m regex
  makeRegexOptsM ::
    (Monad m) => compOpt -> execOpt -> source -> m regex
        -- Defined in Text.Regex.Base.RegexLike

1 个答案:

答案 0 :(得分:4)

您的第一次尝试不起作用,因为makeRegex具有多态返回类型(称为regex)。由于没有针对abitrary类型的RegexMaker实例,您将收到您所做的消息。

要使其工作,您需要指定返回类型。看起来你自己想出来了,因为这就是你在第二次尝试时所做的事情,当我在我的ghci中尝试时,它会顺便发挥作用。

编辑:我应该补充一点,使用regexen的最直接的方法就是使用=~而不用费用makeRegex。例如:

> "lale" =~ ".*" :: Bool
True

> "lale" =~ "lo" :: Bool
False

> "lale" =~ "l." :: String
"la"

> "lale" =~ "l." :: [String]
["la","le"]