[Haskell-beginners] How to write the FromJSON instance for CUid

David McBride toad3k at gmail.com
Thu Aug 9 17:10:48 UTC 2018


Sorry I really should've tested my code before I hit send.

instance FromJSON CUid where
  parseJSON (Number n) = do
    case floatingOrInteger n of
      Right i | inrange i -> return . CUid . fromIntegral $ i
      _ -> mempty

    where
      inrange :: Integer -> Bool
      inrange i = i >= fromIntegral (minBound @Word32) &&
                  i <= fromIntegral (maxBound @Word32)

  parseJSON _ = mempty


On Thu, Aug 9, 2018 at 1:06 PM, David McBride <toad3k at gmail.com> wrote:

> You have to worry about json having a floating point number or an integer
> that is too large to be represented in a Word32, although you could also
> just let it overflow if you don't care too much.  There's probably an
> easier way to do this, but this is what I came up with.
>
> instance FromJSON CUid where
>   parseJSON (Number n) = do
>
>     case floatingOrInteger n of
>       Right i | inrange i -> return . CUid . fromIntegral $ i
>
>      -- not an integer, or not in range
>       _ -> mempty
>
>     where
>       inrange :: Integer -> Bool
>       inrange i = fromIntegral i >= (minBound @Word32) &&
>                     fromIntegral i <= (maxBound @Word32)
>
>   -- not a number
>   parseJSON _ = mempty
>
>
> On Thu, Aug 9, 2018 at 11:37 AM, PICCA Frederic-Emmanuel <
> frederic-emmanuel.picca at synchrotron-soleil.fr> wrote:
>
>> Hello, I try to write the instance for the CUid[1] type
>> But I do not know what to do.
>>
>> instance FromJSON CUid where
>>     parseJSON = ...
>>     {-# INLINE parseJSON #-}
>>
>> Thansk for your help
>>
>>
>> [1] https://hackage.haskell.org/package/base-4.11.1.0/docs/Syste
>> m-Posix-Types.html#t:CUid
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20180809/98f28d44/attachment.html>


More information about the Beginners mailing list