Send Beginners mailing list submissions to
[email protected]
To subscribe or unsubscribe via the World Wide Web, visit
http://www.haskell.org/mailman/listinfo/beginners
or, via email, send a message with subject or body 'help' to
[email protected]
You can reach the person managing the list at
[email protected]
When replying, please edit your Subject line so it is more specific
than "Re: Contents of Beginners digest..."
Today's Topics:
1. Reading JSON using Text.JSON (Adrien Haxaire)
2. Re: Generic exception available? (Antoine Latter)
3. Re: Reading JSON using Text.JSON (Magnus Therning)
4. Re: Multiple versions (Tom Murphy)
5. Re: Reading JSON using Text.JSON (Michael Xavier)
6. Re: Reading JSON using Text.JSON (Christopher Done)
----------------------------------------------------------------------
Message: 1
Date: Sun, 15 May 2011 21:51:28 +0200
From: Adrien Haxaire <[email protected]>
Subject: [Haskell-beginners] Reading JSON using Text.JSON
To: Haskell Beginners <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Hello,
I have this JSON string that I have put in a text file, test.json:
{"coordinates": [0.0, 1.0]}
using GHCi, I can read it like this:
> s <- readFile "test.json"
> let r = decode s :: Result JSValue
> r
Ok (JSObject (JSONObject {fromJSObject = [("coordinates",JSArray
[JSRational False (0 % 1),JSRational False (1 % 1)])]}))
I want to affect this array of two Double to the type Coordinates being
defined like this:
type Coordinates = (Double, Double)
Using this type I can create a Node:
data Node = Node Coordinates Number
deriving (Eq, Ord, Show)
The problem is that I have no idea what to do with decoded JSValue. It
seems I have to define an instance of JSON to read it. Does this mean
using pattern matching to extract the values ?
What do I do with the Result type ? Should I get rid of it like this:
fromResult :: Result JSValue -> JSValue
fromResult (Ok js) = js
fromResult _ = JSNull
and work with the raw JValue ?
These questions might be trivial, but I know only imperative languages,
which is why I like so much to learn Haskell and functional programming,
lots to learn and discover :)
Many thanks in advance,
Adrien
------------------------------
Message: 2
Date: Sun, 15 May 2011 15:09:32 -0500
From: Antoine Latter <[email protected]>
Subject: Re: [Haskell-beginners] Generic exception available?
To: Daniel Fischer <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8
On Sun, May 15, 2011 at 1:23 PM, Daniel Fischer
<[email protected]> wrote:
> On Sunday 15 May 2011 18:53:32, Christopher Howard wrote:
>> I have one spot in some code where I just want to raise an exception
>> that contains the message "Database is formatted incorrectly." Is there
>> some kind of generic way to throw that (like, e.g., in Ruby you just
>> call 'raise "exception message"'. In this case, I don't particularly
>> want to take the time to think about creating an Exception type or
>> finding a suitable one.
>
> Well, the simple thing would be calling
>
> error "Database is formatted incorrectly."
>
> which raises an exception of type ErrorCall.
> If you don't know what type of exception you should throw, ErrorCall might
> fit.
>
>>
>> (BTW: Is there a hierarchical list of standard Haskell Exception
>> instances somewhere?)
>
> There's no hierarchy, either a type is an instance of Exception or not,
> since there's no inheritance, there's no hierarchy (unless you count the
> universal Exception-wrapper SomeException, in which case we'd have a two-
> level hierarchy with that on top).
>
> The haddock docs for the Exception class in Control.Exception [to be found
> locally, on hackage, or on the ghc page] list the known instances.
>
The documentation for Control.Exception lists an example of how to
create an exception hierarchy:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exception-Base.html#t:Exception
You can also create somehting like a hierarchy with ADTs:
> data MyException
> = IOEx IOException
> | Arith ArithException
> | Assert AssertionFailed
> deriving (Show, Typeable)
> instance Exception MyException where
> toException (IOEx e) = toException e
> toException (Arith e) = toException e
> toException (Assert e) = toException e
> fromException (fromException -> Just e) = Just (IOEx e)
> fromException (fromException -> Just e) = Just (Arith e)
> fromException (fromException -> Just e) = Just (Assert e)
You can even catch something as an 'IOException' even if it was thrown
as a 'MyException', or the other way around (it is the same with the
method described in the above link).
(Note that my example above uses ViewPatterns, a GHC extension. It can
be done without, but I am lazy.)
I'm not sure how useful the ADT approach is, but I think it is neat
what can be done with the extensible exceptions.
Antoine
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
------------------------------
Message: 3
Date: Sun, 15 May 2011 22:20:19 +0100
From: Magnus Therning <[email protected]>
Subject: Re: [Haskell-beginners] Reading JSON using Text.JSON
To: [email protected]
Message-ID: <20110515212019.GB5576@ohann>
Content-Type: text/plain; charset="us-ascii"
I wrote down some stuff from my first look at json, maybe it can
help you in getting further?
http://therning.org/magnus/archives/719
/M
On Sun, May 15, 2011 at 09:51:28PM +0200, Adrien Haxaire wrote:
> Hello,
>
> I have this JSON string that I have put in a text file, test.json:
>
> {"coordinates": [0.0, 1.0]}
>
> using GHCi, I can read it like this:
>
> > s <- readFile "test.json"
> > let r = decode s :: Result JSValue
> > r
> Ok (JSObject (JSONObject {fromJSObject = [("coordinates",JSArray
> [JSRational False (0 % 1),JSRational False (1 % 1)])]}))
>
> I want to affect this array of two Double to the type Coordinates
> being defined like this:
>
> type Coordinates = (Double, Double)
>
> Using this type I can create a Node:
>
> data Node = Node Coordinates Number
> deriving (Eq, Ord, Show)
>
> The problem is that I have no idea what to do with decoded JSValue.
> It seems I have to define an instance of JSON to read it. Does this
> mean using pattern matching to extract the values ?
>
> What do I do with the Result type ? Should I get rid of it like this:
>
> fromResult :: Result JSValue -> JSValue
> fromResult (Ok js) = js
> fromResult _ = JSNull
>
> and work with the raw JValue ?
>
> These questions might be trivial, but I know only imperative
> languages, which is why I like so much to learn Haskell and
> functional programming, lots to learn and discover :)
>
> Many thanks in advance,
> Adrien
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
--
Magnus Therning OpenPGP: 0xAB4DFBA4
email: [email protected] jabber: [email protected]
twitter: magthe http://therning.org/magnus
Perl is another example of filling a tiny, short-term need, and then
being a real problem in the longer term.
-- Alan Kay
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL:
<http://www.haskell.org/pipermail/beginners/attachments/20110515/e1fefb4f/attachment-0001.pgp>
------------------------------
Message: 4
Date: Sun, 15 May 2011 17:32:16 -0400
From: Tom Murphy <[email protected]>
Subject: Re: [Haskell-beginners] Multiple versions
To: Mark Bestley <news{@bestley.co.uk>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Thank you! Everything is going smoothly now.
Tom
On 5/15/11, Mark Bestley <news{@bestley.co.uk> wrote:
> Tom Murphy <[email protected]> wrote:
>
>> My god! Another ghci!
>>
>> Thanks for helping me find that.
>>
>> Re-running the Haskell Platform installer ends with an "Installation
>> Failed," and I know enough to not start swapping out binaries in
>> /opt/local/bin, so is there a best-practices way to fix this?
>>
>
> If the other is in /opt/local/bin then this is probably from Macports
> and so you need to remove it.
>
> I had this issue and had to unintsll haskell and its varias ports
>
> so
>
> port uninstall x
> where x was haskell-platform, hs-platform-cabal ,
> hs-platform-haskell-src and anyother hs*
>
> If you dion't use macports for anything then see
> <http://guide.macports.org/#installing.macports.uninstalling>
>
>
> --
> Mark
>
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
------------------------------
Message: 5
Date: Sun, 15 May 2011 16:11:52 -0700
From: Michael Xavier <[email protected]>
Subject: Re: [Haskell-beginners] Reading JSON using Text.JSON
To: Adrien Haxaire <[email protected]>
Cc: Haskell Beginners <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
This isn't submitted as an answer to your question but having used Text.JSON
before in a project, for this one or maybe the next project you work on, you
might want to consider using Aeson. I find the API way nicer to work with
and it is apparently quite performant.
On Sun, May 15, 2011 at 12:51 PM, Adrien Haxaire
<[email protected]>wrote:
> Hello,
>
> I have this JSON string that I have put in a text file, test.json:
>
> {"coordinates": [0.0, 1.0]}
>
> using GHCi, I can read it like this:
>
> > s <- readFile "test.json"
> > let r = decode s :: Result JSValue
> > r
> Ok (JSObject (JSONObject {fromJSObject = [("coordinates",JSArray
> [JSRational False (0 % 1),JSRational False (1 % 1)])]}))
>
> I want to affect this array of two Double to the type Coordinates being
> defined like this:
>
> type Coordinates = (Double, Double)
>
> Using this type I can create a Node:
>
> data Node = Node Coordinates Number
> deriving (Eq, Ord, Show)
>
> The problem is that I have no idea what to do with decoded JSValue. It
> seems I have to define an instance of JSON to read it. Does this mean using
> pattern matching to extract the values ?
>
> What do I do with the Result type ? Should I get rid of it like this:
>
> fromResult :: Result JSValue -> JSValue
> fromResult (Ok js) = js
> fromResult _ = JSNull
>
> and work with the raw JValue ?
>
> These questions might be trivial, but I know only imperative languages,
> which is why I like so much to learn Haskell and functional programming,
> lots to learn and discover :)
>
> Many thanks in advance,
> Adrien
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
--
Michael Xavier
http://www.michaelxavier.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
<http://www.haskell.org/pipermail/beginners/attachments/20110515/3d390291/attachment-0001.htm>
------------------------------
Message: 6
Date: Mon, 16 May 2011 01:37:50 +0200
From: Christopher Done <[email protected]>
Subject: Re: [Haskell-beginners] Reading JSON using Text.JSON
To: Adrien Haxaire <[email protected]>
Cc: Haskell Beginners <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"
On Sun, May 15, 2011 at 09:51:28PM +0200, Adrien Haxaire wrote:
> > The problem is that I have no idea what to do with decoded JSValue.
> > It seems I have to define an instance of JSON to read it. Does this
> > mean using pattern matching to extract the values ?
>
It's correct that you should define an instance of JSON to have a to/from
JSON mapping for your data type. It's not required, but it's a very good
pattern. All parsing is done using the instances. As you can see,
?> :t decode
decode :: (JSON a) => String -> Result a
internally, this function uses the JSON class's readJSON method. The return
value is thus polymorphic.
?> decode "1" :: Result JSValue
Ok (JSRational False (1 % 1))
?> decode "1" :: Result Integer
Ok 1
I have this JSON string that I have put in a text file, test.json:
>
> {"coordinates": [0.0, 1.0]}
>
There is a tuple instance of JSON that you can use to parse the JSON tuple.
instance (JSON a, JSON b) => JSON (a, b)
?> decode "[1,2]" :: Result (Double,Double)
Ok (1.0,2.0)
And for parsing objects, you use the JSObject data type:
?> decode "{\"coordinates\":[1,2]}" :: Result (JSObject (Integer,Integer))
Ok (JSONObject {fromJSObject = [("coordinates",(1,2))]})
Once you're done parsing you have either Ok or Error and you handle it
accordingly.
data Node = Node Coordinates Number
deriving (Eq, Ord, Show)
As far as implementing an instance for your data type goes, you write it
like this:
instance JSON Node where
readJSON object = do obj <- readJSON object
coords <- valFromObj "coordinates" obj
return (Node coords 0)
showJSON (Node coords integer) = makeObj [("coordinates",showJSON coords)]
And then you can use decode for your data type:
?> decode "{\"coordinates\":[1,2]}" :: Result Node
Ok (Node (1.0,2.0) 0)
?> encode (Node (1.0,2.0) 0)
"{\"coordinates\":[1,2]}"
To make the code nicer to read and feel more declarative, you can use the
Applicative instance of JSON:
readJSON object = do obj <- readJSON object
Node <$> valFromObj "coordinates" obj
<*> pure 0
This is equivalent to the lines above. It's nicer like this because with
more parameters to the type, it still remains readable. Let's say you want
to include the number in the JSON parsing, no problem:
readJSON object = do obj <- readJSON object
Node <$> valFromObj "coordinates" obj
<*> valFromObj "number" obj
?> decode "{\"coordinates\":[1,2],\"number\":42}" :: Result Node
Ok (Node (1.0,2.0) 42)
Or let's say you want to make number optional. That's easy with the
Alternative instance of JSON:
readJSON object = do obj <- readJSON object
Node <$> valFromObj "coordinates" obj
<*> (valFromObj "number" obj <|> pure 0)
?> decode "{\"coordinates\":[1,2],\"number\":42}" :: Result Node
Ok (Node (1.0,2.0) 42)
?> decode "{\"coordinates\":[1,2]}" :: Result Node
Ok (Node (1.0,2.0) 0)
And finally, for extracting the value, as you basically figured out above,
you just pattern match on the Ok/Error:
?> case decode "{\"coordinates\":[1,2]}" of
Ok (Node (x,y) n) -> do putStrLn $ "Coords: " ++ show (x,y)
putStrLn $ "Number: " ++ show n
Error msg -> do putStrLn $ "Failed: " ++ msg
Coords: (1.0,2.0)
Number: 0
That's pretty much the whole pattern.
Or if you hate pattern matching, you can define a maybe/either-like
function:
result :: (String -> b) -> (a -> b) -> Result a -> b
result f g (Error x) = f x
result f g (Ok a) = g a
?> result (const $ putStrLn ":(") (putStrLn.show) $ (decode
"{\"coordinates\":[1,2]}" :: Result Node)
Node (1.0,2.0) 0
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
<http://www.haskell.org/pipermail/beginners/attachments/20110516/72bd8714/attachment.htm>
------------------------------
_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners
End of Beginners Digest, Vol 35, Issue 32
*****************************************