简体   繁体   English

在Haskell的复合函数中替换函数

[英]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? 我正在尝试熟悉Haskell,并且想知道是否可以进行以下操作,如果可以,如何进行?

Say I have a set of functions {f,g,..} for which I was to define a replacement function {f',g',..} . 假设我有一组函数{f,g,..} ,我将为其定义替换函数{f',g',..} Now say I have a function c which uses these functions (and only these functions) inside itself eg cx = g (fx) . 现在说我有一个函数c ,它在内部使用这些函数(并且仅这些函数),例如cx = g (fx) Is there a way to automatically define c' x = g' (f' x) without explicitly defining it? 有没有一种方法可以自动定义c' x = g' (f' x)而不显式定义它?

EDIT: By a replacement function f' I mean some function that is conceptually relates to f by is altered in some arbitrary way. 编辑:通过替换函数f'我的意思是某些与f相关的f以任意方式更改。 For example, if f xs ys = (*) <$> xs <*> ys then f' (x:xs) (y:ys) = (x * y):(f' xs ys) etc. 例如,如果f xs ys = (*) <$> xs <*> ysf' (x:xs) (y:ys) = (x * y):(f' xs ys)等。

Many thanks, Ben 非常感谢,本

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. 如果像您的示例那样, ff'具有相同的类型等,那么您可以轻松地将它们作为附加参数传递。 Like 喜欢

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

...which BTW could also be written cGen = (.) ... ...哪个BTW也可以写成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

The most concise and reliable way to do something like this would be with RecordWildCards 进行此类操作的最简洁,最可靠的方法是使用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. 接近所需的唯一方法是使用Template Haskell解析源并进行修改。 Regular Haskell code simply cannot inspect a function in any way - that would violate referential transparency. 常规的Haskell代码根本无法以任何方式检查函数-这会违反参照透明性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM