Is it possible to define a function on a subset of an existing type?

后端 未结 5 1731
夕颜
夕颜 2021-01-18 04:40

I\'m new to Haskell and would like to know whether it\'s possible to define a function that is only defined on a subset of an already existing type, without actually having

5条回答
  •  生来不讨喜
    2021-01-18 05:16

    Wrap the subset in a newtype

    newtype EvenInteger = EvenInteger {
        unEvenInteger :: Integer
    } deriving (Show, Eq, Ord, Num)
    
    mkEvenInteger :: Integer -> Maybe EvenInteger
    mkEvenInteger n = case n % 2 of
        0 -> Just $ EvenInteger n
        _ -> Nothing
    
    squared :: EvenInteger -> EvenInteger
    squared n = n * n
    

提交回复
热议问题