Rewriting an irregular haskell function

I learned about fatigue and the use of $ in functions in haskell, but I'm still having problems converting an unidentified function into something less mysterious.

I get a function

apple = map $ uncurry $ flip ($) 

and I understand that this takes a list of tuples and refers to the corresponding function in the tuple to the variable inside. So I'm trying to rewrite it as

 apple ls = foldr function _ ls where function (a,b) c = (uncurry b) (a,c) 

I get the error for _ as a parsing error, and I have no idea which starting point to use. I need to make it polymorphic, and I understand that this will most likely not be a way to make it less mysterious. Any ideas? They will be very grateful

+6
source share
2 answers

Apple has type

 apple :: [(a, a->b)] -> [b] 

We could rewrite it as

 apple ls = map (\(a, f) -> fa) ls 

So it’s very convenient to write this with foldr ,

 apple ls = foldr (\(a, f) rest -> fa : rest) [] ls 

Or, we can rewrite this in pointfree

 apple = foldr ( (:) . (uncurry . flip $ ($)) ) [] 

The reason for the parsing error is that _ is a special syntax for "variables that I don't need." This will allow you to write things like

  foo _ _ _ _ a = a 

And do not get an error about duplicate variables. Basically, we just populated _ start empty list and fixed a function to add to c instead of trying to apply it to a .

If I wanted to write this in the clearest way, then the original

 apple = map . uncurry . flip $ ($) 

Very nice.

+7
source

The key to understanding is eliminating complexity.

Thus, I suggest that you first deal with one tuple. Write the following function:

  tapp :: (a, a ->b) -> b 

in terms of ($) and flip and uncurry . (To make it even easier, you can first do it for a tuple (a -> b, a) ).

Next, make yourself clear how the map works: if you have a function f :: (a -> b) , then map f will be a function [a] -> [b] . Therefore, map tapp does what you want.

Now you can replace tapp in map (tapp) with this definition (these are the advantages of referential transparency). And that should bring you back to your original expression. Moreover, because, for example:

 f $ gh 

can write

 f (gh) 

or

 (f . g) h 
+1
source

Source: https://habr.com/ru/post/956607/


All Articles