Can I define parametric data type where parameters are not equals between in Haskell?

雨燕双飞 提交于 2019-12-10 22:59:38

问题


Problem:

Let's imagine we have a Passenger with start and end points represented by:

data Passenger a = Passenger { start :: a
                               , end :: a
                             }

Question:

How can I apply a class constraints to Passenger, where the start point shouldn't be equal to the end point?

P.S.: I have asked a similar question in the Scala community, but I didn't receive any answer. Considering that refined library for scala is inspired by refined for Haskell, also hearing about liquid-Haskell, I wonder how can resolve it using Haskell?


回答1:


I just saw this. You can do so by specifying a refinement on the end field, e.g.:

{-@ data Passenger a = Passenger 
      { start :: a
      , end   :: {v:a | v /= start} 
      } 
  @-}

data Passenger a = Passenger 
  { start :: a
  , end   :: a
  }                        

ok :: Passenger String 
ok = Passenger "Alice" "Jones"

bad :: Passenger String
bad = Passenger "Bora" "Bora"

You can play with this online here:

http://goto.ucsd.edu:8090/index.html#?demo=permalink%2F1551137259_16583.hs



来源:https://stackoverflow.com/questions/53961764/can-i-define-parametric-data-type-where-parameters-are-not-equals-between-in-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!