Reputation:
I am fairly new to haskell and I run into this problem with type converting a function. Let's say I don't know anything about a function other than its function type. Is it possible to convert its function type and put it as a new function. For example
myfunc:: (Int -> Int -> Int) -> (Integer -> Integer -> Integer)
myfunc inputfunc = (function with type (Integer -> Integer -> Integer))
Are there ways to do such a thing?
Upvotes: 2
Views: 1118
Reputation: 2167
As already explained by others, what you want is basically this:
convert f x y = fromIntegral (f (fromIntegral x) (fromIntegral y))
This is pretty straightforward. However, if I were to do it, I'd take advantage of the on
function from Data.Function
, which converts the inputs of functions that take two arguments before applying it. So, in your example, it would look like this:
convert f x y = fromIntegral ((f `on` fromIntegral) x y)
I, personally, would go one step further and make this function point-free, but because on f fromIntegral
expects two arguments, you can't just use (.)
, so I usually define an operator for this:
(.:) = (.) . (.)
You can figure out why this works on your own if you'd like, but now I can define convert as this:
convert f = fromIntegral .: (f `on` fromIntegral)
I feel that this is a lot more readable, but I am biased because I have been coding Haskell like this for a while now.
Also, if you look at the inferred type of this variable, you'd see that it's much more general than what you wanted:
convert :: (Integral a, Integral a1, Num b, Num b1) = (b1 -> b1 -> a) -> a1 -> a1 -> b
Anyway, I hope this is somewhat useful.
I really don't mean for this post to intimidate you as a newcomer, so if any of it confuses you, please ask me questions and I'd happily answer :)
Upvotes: 1
Reputation: 10941
Hints:
(Int -> Int -> Int) -> (Integer -> Integer -> Integer)
can also be written (Int -> Int -> Int) -> Integer -> Integer -> Integer
. It is a function of three arguments.
Upvotes: 2