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. Re:  Reading JSON using Text.JSON (Christopher Done)
   2. Re:  Genetic algorithm for knapsack problem (Karol Samborski)
   3. Re:  Reading JSON using Text.JSON (Adrien Haxaire)


----------------------------------------------------------------------

Message: 1
Date: Mon, 16 May 2011 01:38:02 +0200
From: Christopher Done <[email protected]>
Subject: Re: [Haskell-beginners] Reading JSON using Text.JSON
To: Magnus Therning <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"

On 15 May 2011 23:20, Magnus Therning <[email protected]> wrote:

> 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


FWIW, rather than:

readJSON (JSObject obj) = let
        jsonObjAssoc = fromJSObject obj
    in do
        para <- mLookup "para" jsonObjAssoc >>= readJSON
        seeAlso <- mLookup "GlossSeeAlso" jsonObjAssoc >>= readJSON
        return $ GlossDef
            { glossDefPara = para
            , glossDefSeeAlso = seeAlso
            }

You can just write:

readJSON object = do obj <- readJSON object
                     GlossDef <$> valFromObj "para" obj
                              <*> valFromObj "GlossSeeAlso" obj
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
<http://www.haskell.org/pipermail/beginners/attachments/20110516/e17f6706/attachment-0001.htm>

------------------------------

Message: 2
Date: Mon, 16 May 2011 09:58:10 +0200
From: Karol Samborski <[email protected]>
Subject: Re: [Haskell-beginners] Genetic algorithm for knapsack
        problem
To: Biginners Haskell Mailinglist <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

I wrote this for now and it's working pretty well ;)

Any comments?

import AI.SimpleEA
import AI.SimpleEA.Utils

import Control.Monad.Random
import Data.List
import System.Environment (getArgs)
import Control.Monad (unless)

data Item = Item {
    mass  :: Double,
    value :: Double
    }

instance Show Item where
    show i = "(" ++ show (mass i) ++ "," ++ show (value i) ++ ")"

type Gene = (Bool, Item)

capacity = 10.0
items = [  Item 5.0 0.2
         , Item 2.4 0.8
         , Item 1.7 1.9
         , Item 6.0 0.5
         , Item 0.5 0.1
         , Item 2.2 1.2
         , Item 1.4 7.8
         , Item 0.7 1.4
         , Item 6.9 0.3
         , Item 1.5 0.2
         , Item 4.2 0.5
        ]
genes = [ zip [True,  False, True,  True,  False, True,  False, True,
True,  True, True ] items
        ,zip [True,  True, False, False, True, True,  True, False,
False, True, True ] items
        ,zip [False, False, False, False, False, False,  True, False,
False, True, True ] items
        ,zip [False, True, False, True,  True, True,  True, False,
True,  True, True ] items
        ,zip [False, True, False, True,  True, False, False, False,
True,  False, False] items
       ]

fitness :: FitnessFunc Gene
fitness g _
    | massSum > capacity = 0.0
    | otherwise          = valSum
  where
    massSum = foldr (\i s -> s + (mass  $ snd i) ) 0.0 $ filter fst g
    valSum  = foldr (\i s -> s + (value $ snd i) ) 0.0 $ filter fst g

select :: SelectionFunction Gene
select gs = select' (take 4 $ elite gs)
    where scaled = zip (map fst gs) (sigmaScale (map snd gs))
          select' gs' =
              if length gs' >= length gs
                 then return gs'
                 else do
                     p1 <- fitPropSelect scaled
                     p2 <- fitPropSelect scaled
                     let newPop = p1:p2:gs'
                     select' newPop

recombination :: Double -> RecombinationOp Gene
recombination p (g1,g2) = do
    t <- getRandomR (0.0, 1.0)
    if t < p
       then do
           r <- getRandomR (0, length g1-1)
           return (take r g1 ++ drop r g2, take r g2 ++ drop r g1)
       else return (g1,g2)

mutate :: Double -> MutationOp Gene
mutate p g = do
    t <- getRandomR (0.0, 1.0)
    if t < p
       then do
           r <- getRandomR (0, length g-1)
           return (take r g ++ flipItem (g !! r) : drop (r+1) g)
       else return g
        where
              flipItem (False, i) = (True,  i)
              flipItem (True,  i) = (False, i)

main = do
    args <- getArgs
    g <- newStdGen
    let (g1,g2) = split g
    let gs = take 401 $ runEA genes fitness select (recombination
0.75) (mutate 0.01) g2
    let fs = avgFitnesses gs
    let ms = maxFitnesses gs
    let ds = stdDeviations gs
    mapM_ print $ zip5 (map head gs) [1..] fs ms ds
    unless (null args) $ writeFile (head args) $ getPlottingData gs

Regards,
Karol Samborski



------------------------------

Message: 3
Date: Mon, 16 May 2011 10:44:32 +0200
From: Adrien Haxaire <[email protected]>
Subject: Re: [Haskell-beginners] Reading JSON using Text.JSON
To: <[email protected]>
Cc: Haskell Beginners <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8; format=flowed

 Wow, that's a very nice tutorial, thanks a lot Christopher for taking 
 time to explain it to me with so much details. ? really appreciate it.

 I will try to have it working tonight (ie 20:00 GMT +1) and let you 
 know.

 Michael, aeson looks interesting. I may give it a try if/when needed, 
 but for know I prefer to focus on the Text.JSON module to learn Haskell, 
 as it is the default one.

 I keep you updated as soon as I have it working (or not), and thanks 
 again for the help !

 Adrien




 On Mon, 16 May 2011 01:37:50 +0200, Christopher Done wrote:
> 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 Coordin
>
>> d; padding-left: 1ex; "> ? ? ? ?
> Eq, Ord, Show)
>
> As far as implementing an instance for your data type goes, you write
> it like this:
>
> instance JSON Node where
> ??readJSON o
>
>> (Node coords integer) = makeObj [("co
> t;,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  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




------------------------------

_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners


End of Beginners Digest, Vol 35, Issue 33
*****************************************

Reply via email to