Eric
Eric

Reputation: 1531

Pass same argument to function twice

In Elm, is there a higher-order function to transform a function that takes two arguments of the same type into a function that takes one argument and passes it as both arguments to the original function?

Such a function would have the following signature:

twiceTo: (a -> a -> b) -> (a -> b)

And it could be used to define, for example, these functions.

square = twiceTo (*)
tuplize = twiceTo (,)

square 4 -- returns 16
tuplize 1 -- returns (1, 1)

It would be easy to define the function as twiceTo func a = func a a, but does this function exist in the core library or any other libraries? And more importantly, is there a way to compose this function out of the higher-order helpers in the core libraries like always, identity, >>, |>, and friends? It would be nice to use it inline without having to declare extra functions or use anonymous functions.

Upvotes: 3

Views: 284

Answers (1)

Søren Debois
Søren Debois

Reputation: 5688

Such a function is not in Basics.

You can express it inline with a lambda (\x -> ...):

square = (\f x -> f x x) (*)

... but then its clearer to just inline the first operand:

square x = x * x

I don't think there's a way to express twice using only the combinators of Basics, without the lambda.

Upvotes: 4

Related Questions