Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
41 lines (34 loc) · 1.29 KB

File metadata and controls

41 lines (34 loc) · 1.29 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{-# LANGUAGE ScopedTypeVariables #-}
module SimplePersistence
( Id
, Entity
, getId
, persist
, retrieve
) where
import Data.Typeable
-- | Identifier for an Entity
type Id = String
-- | The Entity type class provides generic persistence to txt files
class (Show a, Read a, Typeable a) => Entity a where
-- | return the unique Id of the entity. This function must be implemented by type class instances.
getId :: a -> Id
-- | persist an entity of type a and identified by an Id to a file
persist :: a -> IO ()
persist entity = do
-- compute file path based on entity type and id
let fileName = getPath (typeOf entity) (getId entity)
-- serialize entity as JSON and write to file
writeFile fileName (show entity)
-- | load persistent entity of type a and identified by an Id
retrieve :: Id -> IO a
retrieve id = do
-- compute file path based on entity type and id
let fileName = getPath (typeOf (undefined :: a)) id
-- read file content into string
contentString <- readFile fileName
-- parse entity from string
return (read contentString)
-- | compute path of data file
getPath :: TypeRep -> String -> FilePath
getPath tr id = show tr ++ "." ++ id ++ ".txt"
Morty Proxy This is a proxified and sanitized view of the page, visit original site.