Home > Enterprise >  Can we define a class of function definitions in Haskell?
Can we define a class of function definitions in Haskell?

Time:09-17

Sorry for this title that I picked for a lack of better words.

Here is an typical example of function definition patterns I'm interested in:

h1 :: (Integer, Integer) -> Integer
h1 (x, 0) = f1 x
h1 (x, n) = g1 (x, n)

h2 :: (Integer, Integer) -> Integer
h2 (x, 0) = f2 x
h2 (x, n) = g2 (x, n)

h3 :: (Integer, Integer) -> Integer
h3 (x, 0) = f3 x
h3 (x, n) = g3 (x, n)



f1 :: Integer -> Integer
f1 x = x
g1 :: (Integer, Integer) -> Integer
g1 (x, n) = x

f2 :: Integer -> Integer
f2 x = 0
g2 :: (Integer, Integer) -> Integer
g2 (x, n) = 0

f3 :: Integer -> Integer
f3 x = 2*x
g3 :: (Integer, Integer) -> Integer
g3 (x, n) = x*n

As you can see, lines 1 through 11 are repetitive and exhibit a function definition scheme (and typing) that is common to h1, h2 and h3. This scheme is completed by the definitions that follow. This second part contains the actual "definition content" if I may say.

Is there a way to define a class of function definitions to avoid the repetitions of the first 11 lines?

I hope my question makes sense.

Thank you.

CodePudding user response:

You can construct a helper function that takes as input two functions: an f and a g, and then thus implements the pattern. Such helper thus looks like:

helper :: (Eq b, Num b) => (a -> c) -> ((a, b) -> c) -> (a, b) -> c
helper f g = go
    where go (x, 0) = f x
          go xn = g xn

Then we can use that pattern to define h1 through h3:

h1 :: (Integer, Integer) -> Integer
h1 = helper f1 g1

h2 :: (Integer, Integer) -> Integer
h2 = helper f2 g2

h3 :: (Integer, Integer) -> Integer
h3 = helper f3 g3
  • Related