Ajit
Ajit

Reputation: 675

Checking if a path matches any regex without going through the complete list

Hello am trying to match regular expressions with a FilePath to filter my list of files

import Text.Regex.Posix
import System.FilePath

escapePath path = foldr (&&) True $ map (\pat -> not $  (path =~ pat :: Bool)) patterns
                   where
                       patterns = ["\\.",  "\\.\\.", {-- So on --}]

I believe map and folds would traverse over the complete list before returning a value.

I could avoid using fold by doing something like this

escapePath path = not $ elem True (map (\pat -> (path =~ pat :: Bool)) patterns)
                    where
                       patterns = ["\\.",  "\\.\\.", {-- continued --}]

But still I would be matching the path against all patterns before searching for a value

How can I make the function more efficient by returning a value on first match?

Upvotes: 0

Views: 79

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153087

I believe map and folds would traverse over the complete list before returning a value.

Hey, great, a falsifiable hypothesis, the cornerstone of science! Let's do an experiment to attempt to falsify it. For any value foo, traversing the list foo:undefined completely will throw an exception.

> head (map id (True:undefined))
True
> foldr (&&) True (False:undefined)
False

enter image description here

Upvotes: 6

Related Questions