关闭

一个Hashell模块

322人阅读 评论(0) 收藏 举报
分类:


1.暴露模块的接口

module ModuleName (XXX) where

XXX为暴露的内容


2.导入模块

import XXX

XXX为模块名


3.代码来之Real World Haskell


定义Json

SimpleJSON.hs

module SimpleJSON
    (
        JValue(..)
    ,   getString
    ,   getInt
    ,   getDouble
    ,   getBool
    ,   getObject
    ,   getArray
    ,   isNull
    ) where

data JValue = JString String
            | JNumber Double
            | JBool Bool
            | JNull
            | JObject [(String, JValue)]
            | JArray [JValue]
              deriving (Eq, Ord, Show)

getString :: JValue -> Maybe String
getString (JString s) 		= Just s
getString _           		= Nothing	
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


4.Demo8.hs

module PutJSON where

import Data.List (intercalate)
import SimpleJSON

renderJValue :: JValue -> String

renderJValue (JString s)   = show s
renderJValue (JNumber n)   = show n
renderJValue (JBool True)  = "true"
renderJValue (JBool False) = "false"
renderJValue JNull         = "null"

renderJValue (JObject o) = "{" ++ pairs o ++ "}"
		where 
		pairs [] = ""
		pairs ps = intercalate ", " (map renderPair ps)
		renderPair (k,v)   = show k ++ ": " ++ renderJValue v

renderJValue (JArray a) = "[" ++ values a ++ "]"
		where 
		values [] = ""
		values vs = intercalate ", " (map renderJValue vs)

5.Main.hs

module Main (main) where
import SimpleJSON

main = print (JObject[("foo",JNumber 1),("bar", JBool False)])



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:353370次
    • 积分:8030
    • 等级:
    • 排名:第2637名
    • 原创:433篇
    • 转载:276篇
    • 译文:0篇
    • 评论:14条
    文章分类
    最新评论