到haskell官方下载haskell的工具包:
https://downloads.haskell.org/~platform/2014.2.0.0/Haskell%20Platform%202014.2.0.0%2064bit.signed.pkg
adeMacBook-Pro:haskell_dev apple$ ghci GHCi, version 7.8.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> putStrLn "Hello World" Hello World Prelude>
参考文档:
http://rwh.readthedocs.org/en/latest/chp/1.html
解析:
把下面这段代码保存成SimpleJSON.hs
-- file: ch05/SimpleJSON.hs
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
-- file: ch05/SimpleJSON.hs
getString :: JValue -> Maybe String
getString (JString s) = Just s
getString _ = Nothing
-- file: ch05/SimpleJSON.hs
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool (JBool b) = Just b
getBool _ = Nothing
getObject (JObject o) = Just o
getObject _ = Nothing
getArray (JArray a) = Just a
getArray _ = Nothing
isNull v = v == JNull
main = print (JObject [("foo", JNumber 1), ("bar", JBool False)])
然后在ghci中把add.hs加载进去就可以了:
adeMacBook-Pro:haskell_dev apple$ ghci
GHCi, version 7.8.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :load SimpleJSON.hs
[1 of 1] Compiling Main ( SimpleJSON.hs, interpreted )
Ok, modules loaded: Main.
*Main> getString (JString "hello")
Just "hello"
*Main> getString (JNumber 3)
Nothing
*Main> getString (JString "hello")
Just "hello"
*Main>
编译haskell
adeMacBook-Pro:haskell_dev apple$ ls
Assign.hs InteractWith.hi SimpleJSON.hs WC.o myDrop.hs
BookStore.hs InteractWith.hs WC add.hs quux.txt
HelloWorld.hs InteractWith.o WC.hi hello-in.txt upperCase.hs
InteractWith Maybe WC.hs hello-out.txt
adeMacBook-Pro:haskell_dev apple$ ghc SimpleJSON.hs
[1 of 1] Compiling Main ( SimpleJSON.hs, SimpleJSON.o )
Linking SimpleJSON ...
adeMacBook-Pro:haskell_dev apple$ ls
Assign.hs InteractWith.hs SimpleJSON.hs WC.o quux.txt
BookStore.hs InteractWith.o SimpleJSON.o add.hs upperCase.hs
HelloWorld.hs Maybe WC hello-in.txt
InteractWith SimpleJSON WC.hi hello-out.txt
InteractWith.hi SimpleJSON.hi WC.hs myDrop.hs
adeMacBook-Pro:haskell_dev apple$ ls
Assign.hs InteractWith.hs SimpleJSON.hs WC.o quux.txt
BookStore.hs InteractWith.o SimpleJSON.o add.hs upperCase.hs
HelloWorld.hs Maybe WC hello-in.txt
InteractWith SimpleJSON WC.hi hello-out.txt
InteractWith.hi SimpleJSON.hi WC.hs myDrop.hs
adeMacBook-Pro:haskell_dev apple$ ./SimpleJSON
JObject [("foo",JNumber 1.0),("bar",JBool False)]
使用runghc执行:
adeMacBook-Pro:haskell_dev apple$ runghc SimpleJSON.hs
JObject [("foo",JNumber 1.0),("bar",JBool False)]