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

后端 未结 5 1732
夕颜
夕颜 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:10

    In general no. Such a thing is called a subset type, it's a hallmark of dependent types which Haskell doesn't have. Usually it's implemented by boxing a value with a proof that the value satisfies some property, but since we have no notion of proofs in Haskell, we're stuck.

    Usually the way to fake it is with "smart constructors".

    newtype Even = Even {unEven :: Integer} deriving (Eq, Show, Ord)
    
    toEven :: Integer -> Maybe Even
    toEven a | even a = Just $ Even a
             | otherwise = Nothing
    

    And then hide the Even constructor.

    If you really really want it, you can switch to a language that can interop with Haskell that has dependent types (Coq and Agda spring to mind).

提交回复
热议问题