一个Hashell模块


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)])



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013571243/article/details/46778849
个人分类: Haskell
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

一个Hashell模块

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭