How to simplify this expression?

Consider this:

map fromEnum $ zipWith (==) "aaaa" "abaa" -- [1,0,1,1] 

It would be nice to have only one step here:

 zipWith (\xy -> fromEnum (x == y)) "aaaa" "abaa" 

Now I can exclude y :

 zipWith (\x -> fromEnum.(x ==)) "aaaa" "abaa" 

But I can not exclude x . Of course, there are ways to "cheat" ...

 zipWith (curry (fromEnum . uncurry (==))) "aaaa" "abaa" 

... but it looks uglier than the original lambda.

The function I'm looking for will be somewhat similar to Data.Function.on , but the other way around. I have the feeling that there is an embarrassing simple solution for this. Am I missing something?

+4
source share
3 answers
 zipWith (\x -> fromEnum . (x ==)) "aaaa" "abaa" 

can be written as

 zipWith (\x -> (fromEnum .) (x ==)) "aaaa" "abaa" 

which can be written as

 zipWith ((fromEnum .) . (==)) "aaaa" "abaa" 

If you find that this is readable depends on the taste, I think.

EDIT: Another nice way to do this is with some Matt Hellige combinators :

 zipWith ((==) $. id ~> id ~> fromEnum) "aaaa" "abaa" 
+7
source

There are no predefined library functions that perform exactly this kind of composition of functions that you want here. But if you often use constructs such as the one asked in the question, you can define a function like this:

 (.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d g .: f = \xy -> g (fxy) x = zipWith (fromEnum .: (==)) "aaaa" "abaa" 
+3
source

I defined the following two combinators to prefix partitions (.) :

  • (|.>) : You can read the following definition as: slice f on the right and compose with g .

     (|.>) :: (b -> c) -> (a -> a' -> b) -> (a -> a' -> c) f |.> g = (f .) . g 
  • (<.|) : You can read the following definition of how, slice g on the left and compose with f .

     (<.|) :: (a -> b -> c) -> (a' -> b) -> (a -> a' -> c) f <.| g = (. g) . f 

The direction of the arrow indicates the direction in which the composition occurs. Of these two combinators, the first of them can be used in your example as follows:

 zipWith (fromEnum |.> (==)) "aaaa" "abaa" 
+1
source

All Articles