[Newbie] Why can't I compile this function?

Sorry if this question is too newbie, but I cannot google the answer I want. I am trying to make a partial function out of test from Data.String.Regex (test) for checking against a value with Regex.

import Data.String.Regex (test)

hasClamp :: String -> Boolean
hasClamp = test /clamp/

This looks good to me. However, when I tried to compile it, it returns the following error:

Unable to parse module:
Unexpected or mismatched indentation

I don’t get it. Where have I missed an indentation?

AFAIK there is no regex literals in purescript so you cannot write /clamp/ to represent a regex, but you can use the regex function from Data.String.Regex instead.

2 Likes

As @Lutz already suggested you should probably use regex.

What is sometimes inconvenient is that it returns an Either value but in many cases you have predefined pattern value and you know that it won’t fail. I’m not sure if this is a good advice but… in such a cases you can do somewhat unsafe fromRight call on the top level of the module. This kind of regex constructor will blow up during the first program run (not during compilation!) if it contains a broken pattern:

int = unsafePartial $ fromRight $ regex "[1-9][0-9]*"

This hack is even implemented in the library by Data.String.Regex.Unsafe.unsafeRegex so my example becomes:

int = unsafeRegex "[1-9][0-9]*"
2 Likes

Didn’t realize this until now. Thank you so much!

Cool! This hack is useful and does exactly what I needed. Thank you

I find it is often useful to write regexes with raw string syntax, so you don’t need to deal with string escapes for things like backslashes.

For example, if you want to match multiple *s, you can write

example = unsafeRegex """\*+"""

Rather than

example = unsafeRegex "\\*+"

Which can quickly get quite confusing.

7 Likes