Does Haskell provide an idiom for pattern matching against many possible data constructors?

前端 未结 2 1739
梦如初夏
梦如初夏 2021-01-14 07:45

Working on a Haskell project, I\'m dealing with the Event data type from the FSNotify package. The constructors for Event are all:

         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 08:01

    The simplest way would be to actually reflect the homogenity of the alternatives in the type declaration, instead of just observing it:

    data Action = Added | Modified | Removed
    
    data Event = FileEvent Action FilePath UTCTime | OtherEvent ...
    
    f :: Event -> FilePath
    f (FileEvent _ path _) = path
    

    In general, Haskell has no way to know that all your constructor alternatives have the same number of arguments and the same type, so no, you can't abstract over the choice of alternative.

提交回复
热议问题