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

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

    As mentioned elsewhere, refinement types like in LiquidHaskell can express this. Here's what it looks like:

    module Evens where
    
    {-@ type Even = {v:Int | v mod 2 = 0} @-}
    
    {-@ square :: Even -> Int @-}
    square :: Int -> Int
    square n = n * n
    
    -- calling the function:
    yup = square 4
    -- nope = square 3 -- will not compile if this is uncommented
    

    You can try this out by plugging it in here: http://goto.ucsd.edu:8090/index.html

提交回复
热议问题