Haskell 检查排列的函数
Haskell function to check permutation
如果我声明数据构造函数,例如
data City = Baltimore | Chicago | Seattle | Miami | Toronto
deriving (Bounded, Enum, Eq, Ord, Show)
data Name = Orioles | Cubs | Mariners | Marlins | BlueJays
deriving (Bounded, Enum, Eq, Ord, Show)
如何制作函数
checkPermutation :: (City -> Name) -> Bool
检查没有两个城市分配了相同的团队名称。例如,以下将 return True,但如果任何 "Name" 分配给多个城市,它将 return False。
test1 :: City -> Name
test1 c = case c of
Baltimore -> Orioles
Chicago -> Cubs
Seattle -> Mariners
Miami -> Marlins
Toronto -> Blue Jays
试试这个:
import Data.List (nub)
cities :: [City]
cities = [Baltimore..Toronto]
checkPermutation :: (City -> Name) -> Bool
checkPermutation f = (== length cities) . length . nub . map f $ cities
这基本上是检查函数 f :: City -> Name
是否为 injective。
事实上,我们可以创建一个更通用的injective
谓词:
import Data.Set as Set
typeSet :: (Bounded a, Enum a, Ord a) => Set a
typeSet = fromList $ enumFrom minBound
injective :: (Enum a, Bounded a, Ord a, Ord b) => (a -> b) -> Bool
injective f = let xs = typeSet in (== size xs) . size . Set.map f $ xs
希望对您有所帮助。
如果我声明数据构造函数,例如
data City = Baltimore | Chicago | Seattle | Miami | Toronto
deriving (Bounded, Enum, Eq, Ord, Show)
data Name = Orioles | Cubs | Mariners | Marlins | BlueJays
deriving (Bounded, Enum, Eq, Ord, Show)
如何制作函数
checkPermutation :: (City -> Name) -> Bool
检查没有两个城市分配了相同的团队名称。例如,以下将 return True,但如果任何 "Name" 分配给多个城市,它将 return False。
test1 :: City -> Name
test1 c = case c of
Baltimore -> Orioles
Chicago -> Cubs
Seattle -> Mariners
Miami -> Marlins
Toronto -> Blue Jays
试试这个:
import Data.List (nub)
cities :: [City]
cities = [Baltimore..Toronto]
checkPermutation :: (City -> Name) -> Bool
checkPermutation f = (== length cities) . length . nub . map f $ cities
这基本上是检查函数 f :: City -> Name
是否为 injective。
事实上,我们可以创建一个更通用的injective
谓词:
import Data.Set as Set
typeSet :: (Bounded a, Enum a, Ord a) => Set a
typeSet = fromList $ enumFrom minBound
injective :: (Enum a, Bounded a, Ord a, Ord b) => (a -> b) -> Bool
injective f = let xs = typeSet in (== size xs) . size . Set.map f $ xs
希望对您有所帮助。