Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a nicer way to apply a function to both elements of a pair in a list than a list comprehension?

Tags:

haskell

I use this a fair bit:

a' = [ (f x, f y) | (x, y) <- a ]

Is there a better way to do that?

like image 335
Ali Afshar Avatar asked Oct 23 '12 02:10

Ali Afshar


People also ask

How do you apply a function to each item in a list?

The best way to apply a function to each element of a list is to use the Python built-in map() function that takes a function and one or more iterables as arguments. It then applies the function to each element of the iterables. An alternate way is to use list comprehension.

How do you apply a function to all elements of an array?

B = arrayfun( func ,A1,...,An) applies func to the elements of the arrays A1,...,An , so that B(i) = func(A1(i),...,An(i)) . The function func must take n input arguments and return a scalar.

How do I apply a function to a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.


1 Answers

You can use the (***) operator from Control.Arrow

> map (f *** f) a

or define your own helper function

> let both f (x, y) = (f x, f y)
> map (both f) a
like image 176
hammar Avatar answered Oct 20 '22 00:10

hammar