gpt4 book ai didi

function - 检查排列的 Haskell 函数

转载 作者:行者123 更新时间:2023-12-02 19:33:46 27 4
gpt4 key购买 nike

如果我声明数据构造函数,例如

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com