首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何有效地使用高阶函数?

如何有效地使用高阶函数?
EN

Stack Overflow用户
提问于 2013-02-18 19:24:28
回答 1查看 193关注 0票数 1

通过使用高阶函数,实现函数makeCloths的最佳方式是什么?我希望实现的是makeCloths可以使用methodsList中提供的正确参数自动填充materialList中的每个方法。这样以后如果methodsList中添加了更多方法,并且这些方法只使用materialList中的参数,我们就不需要修改makeCloths中的代码了。

代码语言:javascript
复制
data Material = WhiteCloth Int
              | BlueCloth Int
              | RedCloth Int

makeWhiteShirt :: Material -> Clothe
makeWhiteShirt (WhiteCloth x) = .....

makeBluePants :: Material -> Clothe
makeBluePants (BlueCloth x) = .....

makeRedBlueDress :: Material -> Material -> Clothe
makeRedBlueDress (RedCloth x) (BlueCloth y) = ......

methodsList = [ makeWhiteShirt, makeBluePants, makeRedBlueDress ]
materialList = [ WhiteCloth 3, BlueCloth 2, RedCloth 2]

-- call makeCloths like so
-- listOfClothes = makeCloths methodsList materialList 
makeCloths :: [a] -> [b] -> [Clothe]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-18 19:52:12

首先,正如许多其他人所建议的那样,haskell不允许您拥有基数不匹配的函数数组。您可能希望将衣物类型设置为Material -> makeRedBlueDress。如果你真的想要这种多态性,没有什么能阻止我们为接受多个参数(或由多个Material组成)的Material定义额外的类型。

一旦我们有了它,makeCloths就是zipWith函数的一个特例。

代码语言:javascript
复制
makeCloths = zipWith $ \x y -> (x y)

它的类型签名最有意义

代码语言:javascript
复制
zipWith $ \x y -> (x y) :: [b -> c] -> [b] -> [c]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14935147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档