通过使用高阶函数,实现函数makeCloths的最佳方式是什么?我希望实现的是makeCloths可以使用methodsList中提供的正确参数自动填充materialList中的每个方法。这样以后如果methodsList中添加了更多方法,并且这些方法只使用materialList中的参数,我们就不需要修改makeCloths中的代码了。
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]发布于 2013-02-18 19:52:12
首先,正如许多其他人所建议的那样,haskell不允许您拥有基数不匹配的函数数组。您可能希望将衣物类型设置为Material -> makeRedBlueDress。如果你真的想要这种多态性,没有什么能阻止我们为接受多个参数(或由多个Material组成)的Material定义额外的类型。
一旦我们有了它,makeCloths就是zipWith函数的一个特例。
makeCloths = zipWith $ \x y -> (x y)它的类型签名最有意义
zipWith $ \x y -> (x y) :: [b -> c] -> [b] -> [c]https://stackoverflow.com/questions/14935147
复制相似问题