Lifetime problem with curried function

Ok, in that case you can create a new trait to handle the implementation

trait RegexMatch<E: ParseError<Self>>: Sized {
    fn regex_match(self, regex: &Regex) -> IResult<Self, Self, E>;
}

pub fn regex_match<I, E: ParseError<I>>(re: &Regex) -> impl  Fn(I) -> IResult<I, I, E>
where
    I: RegexMatch<E>
{
    move |input| input.regex_match(re)
}

impl<'a, E: ParseError<&'a str>> RegexMatch<E> for &'a str {
    fn regex_match(self, regex: &Regex) -> Result<Self, Self, E> {
        // impl regex_match here
    }
}

This way regex matching is also generalized over different input types, which is also in line with the rest of nom. For example, you can have regex matching for both &str and &[u8]

2 Likes

This is great, thank you very much! Doing it this way wouldn’t have occured to me.

EDIT: I think the polymorphism isn’t quite that simple because Regex can’t match both &str and &[u8]. There are two different Regex types for that, right?

Well, generalize more, add another generic parameter to RegexMatch that represents the Regex and maybe another trait to control it.

Or you can slightly change the trait to,

trait RegexPattern<I, E: ParseError<I>>: Sized {
    fn regex_match(&self, input: I) -> IResult<I, I, E>;
}

And implement this for Regex.

1 Like

Yes, that’s more or less what I arrived at, only I put the trait on the input type and not on the regex type. Thank you again for the great help!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.