Harvey Adcock
Harvey Adcock

Reputation: 971

How can I make a function that takes a function as an argument and returns a modified version of that function?

Basically I need to create a function in Haskell which takes a function as an argument and returns another function with all the same pattern matching but with one extra pattern to match against. I'm not sure how possible this is and I couldn't find anything on google, but that might be because the title is as concise as I could think how to phrase this problem!

For example, say I had a function defined like this:

example :: String -> Integer
example "a" = 1
example "b" = 2
example _   = 0

and then another function with type:

example2 :: String -> Integer -> (String -> Integer) -> (String -> Integer)
example2 str int f = ?

how could I write the second function so that it would return a function which did exactly the same as the first function, except also return the Integer int when passed the String str?

Upvotes: 1

Views: 109

Answers (1)

user1804599
user1804599

Reputation:

example2 :: String -> Integer -> (String -> Integer) -> (String -> Integer)
example2 s x f = \a -> if a == s then x else f a

Note that this overrides any matching of s by f, i.e. example2 "c" 3 example is equivalent to:

f :: String -> Integer
f "c" = 3
f "a" = 1
f "b" = 2
f _   = 0

Upvotes: 1

Related Questions