Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify this expression?

Tags:

haskell

Consider this:

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

It would be nice to have only one step here:

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

Now I can eliminate y:

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

But I fail to eliminate x. Of course there are ways to "cheat"...

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

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

The function I look for would be somewhat similar to Data.Function.on, but "the other way around". I have the feeling that there is an embarrassingly simple solution for this. Do I overlook something?

like image 838
Landei Avatar asked Dec 21 '22 08:12

Landei


1 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 this readable depends on taste I guess.

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

zipWith ((==) $. id ~> id ~> fromEnum) "aaaa" "abaa"
like image 155
Sjoerd Visscher Avatar answered Jan 25 '23 14:01

Sjoerd Visscher