function - 检查排列的 Haskell 函数

标签 function haskell boolean 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

检查没有为两个城市分配相同的团队名称。例如,以下内容将返回 True,但如果将任何“名称”分配给多个城市,则会返回 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 .

事实上,我们可以创建一个更通用的单射谓词:

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

希望有帮助。

关于function - 检查排列的 Haskell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663739/

相关文章:

我的 createMinHeightBST 函数中的 JavaScript 函数声明范围

c++ - 我的编译器是否混淆了它认为的重载函数?

haskell - 提示符下的单子(monad)?

html - 如何在不使用单选按钮或复选框的情况下将是/否答案编程为 HTML 表单中的按钮?

c++ - 是在没有显式强制转换的情况下使用常量调用未定义的行为吗?

python - 来自未在 python 中导入的模块的函数

haskell - 如何规避 GHC 阶段限制?

Haskell:使用列表理解解析错误(可能是不正确的缩进或不匹配的括号)

python - 通过 boolean 掩码数组选择numpy数组的元素

C# bool 表达式求值顺序