0

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 ?

Bobby
  • 1,585
  • 3
  • 19
  • 42
rogergl
  • 3,501
  • 2
  • 30
  • 49
  • The error message suggests you have the text `return (1 0 :: Integer)` somewhere in your program. Are you sure the code fragment you posted is where the error is coming from? – ErikR Jul 02 '16 at 14:13
  • The error message was wrong. I updated it. – rogergl Jul 02 '16 at 14:27

2 Answers2

1

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)
ErikR
  • 51,541
  • 9
  • 73
  • 124
0

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
rogergl
  • 3,501
  • 2
  • 30
  • 49