BenJacob
BenJacob

Reputation: 987

Replacing functions in composite function in haskell

I'm trying to become familiar with Haskell and I was wondering if the following was possible and if so, how?

Say I have a set of functions {f,g,..} for which I was to define a replacement function {f',g',..}. Now say I have a function c which uses these functions (and only these functions) inside itself e.g. c x = g (f x). Is there a way to automatically define c' x = g' (f' x) without explicitly defining it?

EDIT: By a replacement function f' I mean some function that is conceptually relates to f by is altered in some arbitrary way. For example, if f xs ys = (*) <$> xs <*> ys then f' (x:xs) (y:ys) = (x * y):(f' xs ys) etc.

Many thanks, Ben

Upvotes: 0

Views: 94

Answers (2)

Steven Armstrong
Steven Armstrong

Reputation: 475

The most concise and reliable way to do something like this would be with RecordWildCards

data Replacer ... = R {f :: ..., g :: ...}

c R{..} x = g (f x)

Your set of functions now is now pulled from the local scope from the record, rather than a global definition, and can be swapped out for a different set of functions at your discretion.

The only way to get closer to what you want would to be to use Template Haskell to parse the source and modify it. Regular Haskell code simply cannot inspect a function in any way - that would violate referential transparency.

Upvotes: 0

leftaroundabout
leftaroundabout

Reputation: 120741

If, as seems to be the case with your example, f and f' have the same type etc., then you can easily pass them in as extra parameters. Like

cGen :: ([a] -> [a] -> [a]) -> (([a] -> [a]) -> b) -> [a] -> b
cGen f g x = g (f x)

...which BTW could also be written cGen = (.)...

If you want to group together specific “sets of functions”, you can do that with a “configuration type”

data CConfig a b = CConfig {
       f :: [a] -> [a] -> [a]
     , g :: ([a] -> [a]) -> b
     }

cGen :: CConfig a b -> [a] -> b
cGen (CConfig f g) = f . g

Upvotes: 1

Related Questions