Skip to content
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

Add NonEmpty newtype #18

Closed
wants to merge 1 commit into from
Closed

Conversation

basvandijk
Copy link
Contributor

Hi Johan,

I used this at work and it seems useful in general.

I'm not married to the name at all. It could also be called:

newtype NonNull a = NonNull {nonNull :: a}

Or something similar...

Cheers,

Bas

@basvandijk
Copy link
Contributor Author

Mmm after thinking about it a bit more I realize this type is maybe a bit to specific to my use-case to add to cassava after all. What do you think? Just close it if you think it shouldn't belong here.

@tibbe
Copy link
Collaborator

tibbe commented Nov 13, 2012

I'll keep it in mind if this issue comes up again (which would provide some more support for it being generally useful).

@tibbe tibbe closed this Nov 13, 2012
@basvandijk
Copy link
Contributor Author

No problem. BTW here's another extensible (but possibly overkill) design:

Defined in the core of the library:

newtype FieldPredicate p a = FieldPredicate {unFieldPredicate :: a}
    deriving (Eq, Ord, Read, Show)

instance ToField a => ToField (FieldPredicate p a) where
    toField = toField . unFieldPredicate

instance (Predicate p, FromField a) => FromField (FieldPredicate p a) where
    parseField s
        | unTagged (predicate :: Tagged p (Field -> Bool)) s =
            FieldPredicate <$> parseField s
        | otherwise = fail "Predicate failed"

class Predicate p where
    predicate :: Tagged p (Field -> Bool)

-- or get the one from Edward Kmett's tagged package:
newtype Tagged s b = Tagged { unTagged :: b }

Defined in a utility module or defined by the user herself:

{-# LANGUAGE EmptyDataDecls #-}

data NonEmpty

instance Predicate NonEmpty where
    predicate = Tagged $ not . B.null

nonEmpty :: FieldPredicate NonEmpty a -> a
nonEmpty = unFieldPredicate

To be used in the same way as before:

instance FromRecord Person where
    parseRecord v
        | length v == 2 = Person <$>
                          (nonEmpty <$> v .! 0) <*>
                                        v .! 1
        | otherwise     = mzero

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants