Nic*_*ick 1 haskell max ghci pointfree function-composition
有人可以告诉我为什么在这个功能中使用"." ?
longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (length . fst . snd)
Run Code Online (Sandbox Code Playgroud)
longestProductLen :: [(Barcode, Item)] -> Int
longestProductLen = maximum . map (length . fst . snd)
Run Code Online (Sandbox Code Playgroud)
.是函数组合,所以maximum. map f意味着map f,然后取最大值,所以例如如果f是(+5),那么我们得到
( maximum .map (+5) ) [1,2,3,4]
= maximum (map (+5) [1,2,3,4])
= maximum [6,7,8,9]
= 9
Run Code Online (Sandbox Code Playgroud)
在您提供的代码中,.也用于(length . fst . snd).
请注意,因为longestProductLen :: [(Barcode, Item)] -> Int,如果我们映射f该列表,f则必须接受类型的数据(Barcode, Item).
它需要snd,它给了它一个项目fst,所以它必须是那样type Item = (Product,???).我不知道是什么??? 但是你的功能并不重要.我猜Double.
接下来我们采取length,所以type Product = [????].我怀疑它是[Char],即String,但无论如何,我们可以考虑它的长度.
因此,让我们通过一些示例数据来解决这个问题:
(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
Run Code Online (Sandbox Code Playgroud)
把它放在一起给
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
Run Code Online (Sandbox Code Playgroud)
所以我们发现最长的产品长度为8(来自Emmental).