pro*_*ami 5 sorting haskell compare semigroup
该程序可以按制造或按年份对列表进行排序。什么是 (<>)?
import Data.Semigroup ((<>))
compare = comparing year <> comparing mfg
.
.
.
Run Code Online (Sandbox Code Playgroud)
import Data.Semigroup ((<>))
不会在您的程序中做任何有用的事情,自 2015 年发布 GHC 7.10 以来也没有。在此之前,它将<>
操作符引入范围以便compare = flip (comparing year) <> comparing mfg
可以使用它。在 GHC 7.10 中,该运算符已添加到 Prelude 中,因此即使不导入它,它现在也始终在范围内。
至于<>
那里有什么,你在 type 中使用它Vehicle -> Vehicle -> Ordering
。它来自Semigroup b => Semigroup (a -> b)
实例(两次)和Semigroup Ordering
实例。最终效果是,在应用两者之后Vehicles
,它将使用左侧比较的结果 ( flip (comparing year)
),除非它是EQ
,在这种情况下,它将使用右侧比较 ( comparing mfg
) 代替。如果你要用手准确地写出它在做什么,它会是这样的:
compare x y = case flip (comparing year) x y of
LT -> LT
EQ -> comparing mfg x y
GT -> GT
Run Code Online (Sandbox Code Playgroud)