开发者

Haskell: 'No instance for' arising from a trivial usage of Regex library

Following the (accepted) answer from this question, I am expecting the following to work:

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

(makeRegex is a shortcut for makeRegexOpts with predefined options)

However, it doesn't:

<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 <int开发者_C百科eractive>: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

And I really don't understand why.

EDIT

Haskell Platform 2009.02.02 (GHC 6.10.4) on Windows

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


Your first try does not work because makeRegex has a polymorphic return type (called regex). Since there is no instance of RegexMaker for abitrary types, you get the message you do.

To make it work you need to specify a return type. It seems like you figured that out yourself because that's what you did in your second try, which incidentally works when I try it out in my ghci.

Edit: I should add that the most straight-forward way to use regexen is to just use =~ and not bother with makeRegex at all. For example:

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

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜