有人可以告诉我为什么在这个功能中使用“。” ?
longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (length . fst . snd)
答案 0 :(得分:6)
longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (length . fst . snd)
.
是函数组合,因此maximum. map f
表示地图f
,然后取最大值,例如,如果f
为(+5)
,那么我们得到
( maximum .map (+5) ) [1,2,3,4]
= maximum (map (+5) [1,2,3,4])
= maximum [6,7,8,9]
= 9
在您提供的代码中,.
也使用(length . fst . snd)
。
请注意,自longestProductLen :: [(Barcode, Item)] -> Int
以来,如果我们将f
映射到该列表,f
必须接受(Barcode, Item)
类型的数据。
需要snd
,然后为fst
提供一个项目,因此它必须是type Item = (Product,???)
。我不知道是什么???但这对你的功能并不重要。我猜是Double
。
接下来我们选择length
,type Product = [????]
。我怀疑它是[Char]
,即字符串,但无论如何,我们可以考虑它的长度。
因此,让我们通过一些示例数据进行工作:
(length . fst . snd) ("|| ||| | ||| | || |||| | |", ("Gruyere",1.05))
= (length . fst) (snd ("|| ||| | ||| | || |||| | |", ("Gruyere",1.05)) )
= (length . fst) ("Gruyere",1.05)
= length ( fst ("Gruyere",1.05) )
= length "Gruyere"
= 7
把它放在一起给出了
longestProductLen [("|| ||| | ||| | || |||| | |", ("Gruyere",1.05)),
("| ||| || ||| || |||| || |", ("Emmental",0,97)),
("||||| ||| ||| || | || |||", ("Gouda",1,21))]
= maximum . map (length . fst . snd)
[("|| ||| | ||| | || |||| | |", ("Gruyere",1.05)),
("| ||| || ||| || |||| || |", ("Emmental",0,97)),
("||||| ||| ||| || | || |||", ("Gouda",1,21))]
= maximum [7,8,5]
= 8
所以我们发现最长的产品长度为8(来自Emmental)。
答案 1 :(得分:4)
.
是功能组合。它可以定义为
(.) :: (b->c) -> (a->b) -> a -> c
f . g = \x -> f (g x)
答案 2 :(得分:1)
其他答案都很好,但为了便于阅读,您可以在心理上只在等式的两边添加变量,并用.
或parens替换$
,这样您的示例就会读取:
longestProductLen xs = maximum $ map (\y -> length $ fst $ snd y) xs
供参考:原始版本称为“pointfree style”(“点”不是点而是变量)。