Positive integer type

后端 未结 6 1728
野性不改
野性不改 2020-11-28 10:17

In many articles about Haskell they say it allows to make some checks during compile time instead of run time. So, I want to implement the simplest check possible - allow a

6条回答
  •  失恋的感觉
    2020-11-28 11:09

    module Positive (toPositive, Positive(unPositive)) where
    
    newtype Positive = Positive { unPositive :: Int }
    
    toPositive :: Int -> Maybe Positive
    toPositive n = if (n < 0) then Nothing else Just (Positive n)
    

    The above module doesn't export the constructor, so the only way to build a value of type Positive is to supply toPositive with a positive integer, which you can then unwrap using unPositive to access the actual value.

    You can then write a function that only accepts positive integers using:

    positiveInputsOnly :: Positive -> ...
    

提交回复
热议问题