Calculate module of "Just int" in Haskell

Viewed 147

I'm trying to calculate the module of an index of a list.

list=[5,6,7,8]
a = elemIndex 7 list
b = mod a 2

Ideally, this would give me b = 0 since a = 2 (technically). But I'm getting error messages since a is not 2 but Just 2.

2 Answers

You can just use pattern matching with let to get to the inner part of the Maybe value when it is guaranteed to be Just _:

list = [5,6,7,8]
a = elemIndex 7 list
b = mod a 2

foo list = [b | n <- [5,6,7,8]
              , let a = elemIndex n [5,6,7,8]
              , let Just i = a
              , let b = mod i 2]
         = [b | n <- list
              , let Just i = elemIndex n list
              , let b = mod i 2]
         = [b | (_, i) <- zip list [0..]
              , let b = mod a 2]
         = ls where ls = [0,1] ++ ls

bar list = [(n,b) | n <- list
                  , let Just i = elemIndex n list
                  , let b = mod i 2]
         = [(n,b) | (n, i) <- zip list [0..]
                  , let b = mod i 2]
         = zip list ls where ls = cycle [0,1]

Normally this kind of pattern matching is frowned upon since it is partial, i.e. can cause error if the value is actually Nothing, but here it is correct by construction.

But then really, why put it into a Just -- just use it as it is. And we did.

Related