Ben Moore
Ben Moore

Reputation: 91

How to set limits on each individual Int

I'm trying to change a list of Ints in Haskell to make keep them within specific limits, but it doesn't seem to be working. I'm trying to make every int in the list sit between 32 and 127 but it's not working, could anyone explain why this isn't working?

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

Upvotes: 2

Views: 102

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

Based on your comment, you want to transform Ints that are not in the 32-127 range by applying a modulo transformation. Therefore we can first implement a helper function:

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

This results in:

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

Next our function limitList is only a mapping with that helper:

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

This generates:

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]

Upvotes: 6

Related Questions