Function composition when function parameters in wrong order
I understand that in Haskell it's important to put the most 'variable' argument (aka the input object) last in a function definition, to make the function as composable as possible (reference). But if I'm using a library function that doesn't follow this rule, is there any alternative/workaround to function composition to increase rea开发者_如何学Pythondability?
I'll give a specific example - the subRegex function takes the input string as the first of two arguments, and so chaining two of these plus a toUpper
to create a "slugify" function I have ended up with the below:
slugify :: FilePath -> FilePath
slugify old =
let (dir, file) = splitFileName old
in combine dir $ subRegex (mkRegex "[ _]") (subRegex (mkRegex "[^.a-z0-9_ ]+") (map toLower file) "") "-"
Is there a function-composition-style way of tidying this up given the order of the subRegex arguments?
You can always provide a small helper to change the argument order into something more composable:
slugify :: FilePath -> FilePath
slugify old =
let (dir, file) = splitFileName old
in combine dir $ sub "[ _]" "-" $ sub "[^.a-z0-9_ ]+" "" $ map toLower file
where
sub regex replacement input = subRegex (mkRegex regex) input replacement
In simple cases, you can also use flip
or a lambda expression, but in this case I think a local definition is nicer. It also makes it easy to remove the duplication of the calls to mkRegex
.
精彩评论