Mittenchops
Mittenchops

Reputation: 19724

Multiple regex matches not a [String] in Haskell

I'm looking at the RWH tutorial here, which suggests, but has an error on, the usage of [String] to return multiple results. As you can see:

"I'd like to group by word breaks" =~ "\\S+" :: Bool
"I'd like to group by word breaks" =~ "\\S+" :: String
"I'd like to group by word breaks" =~ "\\S+" :: [[String]]

produce

True
"I'd"
[["I'd"],["like"],["to"],["group"],["by"],["word"],["breaks"]]

respectively.

But the recommended [String] does not, and instead has an error:

"I'd like to group by word breaks" =~ "\\S+" :: [String]

<interactive>:1:1: error:
    • No instance for (RegexContext Regex String [String]) arising from a use of ‘=~’
    • In the expression: "I'd like to group by word breaks" =~ "\\S+" :: [String]
      In an equation for ‘it’: it = "I'd like to group by word breaks" =~ "\\S+" :: [String]

How can I ask for the missing [String]-like type suggestion that would provide what I'm looking for, namely:

["I'd","like","to","group","by","word","breaks"]

without having to post-process? Also, it's interesting that this seems natural in the context of the other successful type conversions, and it even worked this way at one point when the book was written, and no longer does. What is the explanation for the change?

Upvotes: 1

Views: 69

Answers (1)

Mittenchops
Mittenchops

Reputation: 19724

Looks like from the comments on that, the recommendations are either:

Prelude Text.Regex.PCRE> getAllTextMatches ("I'd like to group by word breaks" =~ "\\S+") :: [String]
["I'd","like","to","group","by","word","breaks"]

or

Prelude Text.Regex.PCRE> concat $ "I'd like to group by word breaks" =~ "\\S+" :: [String]
["I'd","like","to","group","by","word","breaks"]

Neither of these are as clean as how this used to work.

Upvotes: 1

Related Questions