Working with local storage in Haste

97 Views Asked by At

I would like to read and write an integer from and to local storage.

My code looks like this (just trying to make this compile so far):

loadFromStorage = do
    mr <- getItem "budget"
    case mr of
        Left _ -> return (0 :: Integer)
        Right _ -> return (1 :: Integer)

But I get:

No instance for (Serialize a0) arising from a use of ‘getItem’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Serialize JSON -- Defined in ‘Haste.Serialize’
      instance Serialize JSString -- Defined in ‘Haste.Serialize’
      instance (Serialize a, Serialize b) => Serialize (Either a b)
        -- Defined in ‘Haste.Serialize’
      ...plus 13 others
    In a stmt of a 'do' block: mr <- getItem "budget"
    In the expression:
      do { mr <- getItem "budget";
           case mr of {
             Left _ -> return (0 :: Integer)
             Right _ -> return (1 :: Integer) } }
    In an equation for ‘loadFromStorage’:
        loadFromStorage
          = do { mr <- getItem "budget";
                 case mr of {
                   Left _ -> return (0 :: Integer)
                   Right _ -> return (1 :: Integer) } }

The questions are:

What must I do to make this code compile ?

What must I do to read and write an integer ?

2

There are 2 best solutions below

0
ErikR On

Even though you are not using mr you need to specify what type it is.

One way to specify the type of mr is to add a let _ = mr :: ... statement:

loadFromStorage = do
    mr <- getItem "budget"
    let _ = mr :: MyType
    case mr of
        Left _ -> return (0 :: Integer)
        Right _ -> return (1 :: Integer)
0
rogergl On

That works for me now:

toStorage :: Int -> IO ()
toStorage n = do
    setItem "page" n
    return ()

fromStorage :: IO Int
fromStorage = do
                 value <- getItem "page"
                 either (\_ -> return 0)
                        (\n -> return n)
                        value