Skip to content

Fix stack overflow in BoundedEnum (Either _ _) #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Data/Enum.purs
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,10 @@ instance boundedEnumEither :: (BoundedEnum a, BoundedEnum b) => BoundedEnum (Eit
Cardinality
$ unwrap (cardinality :: Cardinality a)
+ unwrap (cardinality :: Cardinality b)
toEnum = to cardinality cardinality
toEnum n = to cardinality cardinality
where
to :: Cardinality a -> Cardinality (Either a b) -> Int -> Maybe (Either a b)
to (Cardinality ca) (Cardinality cab) n
to :: Cardinality a -> Cardinality (Either a b) -> Maybe (Either a b)
to (Cardinality ca) (Cardinality cab)
| n >= 0 && n < ca = Left <$> toEnum n
| n >= ca && n < cab = Right <$> toEnum (n - ca)
| otherwise = Nothing
Expand Down
14 changes: 13 additions & 1 deletion test/Test/Data/Enum.purs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE, log)

import Data.Newtype (unwrap)
import Data.Enum (class Enum, class BoundedEnum, defaultToEnum, defaultFromEnum,
defaultCardinality, enumFromTo, enumFromThenTo, upFrom,
downFrom, toEnum)
downFrom, toEnum, fromEnum, Cardinality, cardinality)
import Data.Maybe (Maybe(..))
import Data.Either (Either(..))

import Test.Assert (ASSERT, assert)

Expand Down Expand Up @@ -70,3 +72,13 @@ testEnum = do
assert $ toEnum 1 == Just (Just false) :: Maybe (Maybe Boolean)
assert $ toEnum 2 == Just (Just true) :: Maybe (Maybe Boolean)
assert $ toEnum 3 == Nothing :: Maybe (Maybe Boolean)

log "BoundedEnum (Either _ _)"
assert $ unwrap (cardinality :: Cardinality (Either Boolean Boolean)) == 4
assert $ toEnum 0 == Just (Left false :: Either Boolean T)
assert $ toEnum 1 == Just (Left true :: Either Boolean T)
assert $ toEnum 3 == Just (Right B :: Either Boolean T)
assert $ fromEnum (Left false :: Either Boolean T) == 0
assert $ fromEnum (Left true :: Either Boolean T) == 1
assert $ fromEnum (Right B :: Either Boolean T) == 3