Making a Read instance in Haskell

后端 未结 2 1844
梦如初夏
梦如初夏 2020-12-28 16:38

I have a data type

data Time = Time {hour :: Int,
                  minute :: Int
                 }

for which i have defined the instance

2条回答
  •  有刺的猬
    2020-12-28 17:13

    If the input to readsPrec is a string that contains some other characters after a valid representation of a Time, those other characters should be returned as the second element of the tuple.

    So for the string 12:34 bla, the result should be [(newTime 12 34, " bla")]. Your implementation would cause an error for that input. This means that something like read "[12:34]" :: [Time] would fail because it would call Time's readsPrec with "12:34]" as the argument (because readList would consume the [, then call readsPrec with the remaining string, and then check that the remaining string returned by readsPrec is either ] or a comma followed by more elements).

    To fix your readsPrec you should rename minutePart to something like afterColon and then split that into the actual minute part (with takeWhile isDigit for example) and whatever comes after the minute part. Then the stuff that came after the minute part should be returned as the second element of the tuple.

提交回复
热议问题