如何为每个Int

时间:2017-05-04 19:49:55

标签: list haskell functional-programming

我正在尝试更改Haskell中的Int列表以使其保持在特定限制内,但它似乎不起作用。我试图让列表中的每个int都在32到127之间,但它不起作用,有人可以解释为什么这不起作用吗?

limit :: Int -> Int
limit n | n > 127  = n `mod` 127 + 32
        | n < 32 = n  + 127 - 32
        | otherwise = n

limitList :: [Int] -> [Int]
limitList [] = []
limitList (x:xs) = [limit x] ++ limitList xs

1 个答案:

答案 0 :(得分:6)

根据您的评论,您希望通过应用模数转换来转换32-127范围内Int。因此,我们可以先实现helper函数:

helper x = 32 + mod (x-32) (128-32)

这导致:

Prelude> helper 31
127
Prelude> helper 32
32
Prelude> helper 127
127
Prelude> helper 128
32

接下来,我们的函数limitList仅与该帮助程序进行map ping:

limitList = map helper
    where helper x = 32 + mod (x-32) (128-32)

这会产生:

Prelude> limitList [1,4..256]
[97,100,103,106,109,112,115,118,121,124,127,34,37,40,43,46,49,52,55,58,61,64,67,70,73,76,79,82,85,88,91,94,97,100,103,106,109,112,115,118,121,124,127,34,37,40,43,46,49,52,55,58,61,64,67,70,73,76,79,82,85,88,91,94,97,100,103,106,109,112,115,118,121,124,127,34,37,40,43,46,49,52,55,58,61,64]