2014-10-18 49 views
1

基本上我需要在Haskell中創建一個函數,它將一個函數作爲參數,並返回具有所有相同模式匹配但具有一個額外模式以匹配的另一個函數。我不確定這是多麼可能,我在谷歌上找不到任何東西,但這可能是因爲標題如我能想到的那樣簡潔明瞭這個問題!我該如何製作一個函數,將函數作爲參數並返回該函數的修改版本?

例如,假設我有這樣定義一個函數:

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

,然後另一個功能與類型:

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

我怎麼能寫的第二個功能,這樣它會返回一個函數做了與第一個函數完全相同的函數,除了返回Integer int時傳遞字符串str

+4

如果您在相互嵌套許多這樣的「編輯」,你應該考慮使用數據結構來保存映射而不是函數。例如。 'Data.Map'。 – luqui 2014-10-18 22:22:02

回答

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

注意,這將覆蓋s任何匹配的f,即example2 "c" 3 example相當於:

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