I have a data structure called ClientSession
which I convert to a String
separated by |
for each element and back to the data structure.
18 data ClientSession = ClientSession
19 { sec :: Int
20 , nsec :: Int
21 , username :: String
22 , dbid :: Integer
23 , uuid :: Int
24 , prand :: Int
25 } deriving (Ord, Eq)
26
27 instance Show ClientSession where
28 show (ClientSession
29 { sec = s
30 , nsec = ns
31 , username = un
32 , dbid = db
33 , uuid = ud
34 , prand = pr}) = intercalate "|" ls
35 where ls = [show s, show ns, un, show db, show ud, show pr]
Then I have a set of functions to read
that string and create a ClientSession
from the result. The problem is that this set of functions are so ugly that I lay sleepless at night.
I'm looking for feedback on how to make this code more Haskell. It doesn't feel Haskell to me, it feels like I have solved it in another language and then just ported the code straight off. Like when you translate a natural language in Google Translate.
I have thought of different solutions. Maybe I could use template Haskell, or Typeable/Generics
type classes in some way, or chain the reading using >>=
, or something similar.
I'm still new to Haskell, I've used it on my spare time very little over a couple of years.
37 fromString :: String -> Maybe ClientSession
38 fromString ss = fromParts $ endBy "|" ss
...
74 fromParts :: [String] -> Maybe ClientSession
75 fromParts (s:ns:un:db:ud:pr:[])
76 = newSessionM (readMaybe s) (readMaybe ns) (Just un) (readMaybe db) (readMaybe ud) (readMaybe pr)
77 fromParts _ = Nothing
78
79 newSessionM :: Maybe Int
80 -> Maybe Int
81 -> Maybe String
82 -> Maybe Integer
83 -> Maybe Int
84 -> Maybe Int
85 -> Maybe ClientSession
86 newSessionM (Just s)
87 (Just ns)
88 (Just un)
89 (Just db)
90 (Just ud)
91 (Just pr) = return $ newSession s ns un db ud pr
92 newSessionM _ _ _ _ _ _ = Nothing
93
94 newSession :: Int -> Int -> String -> Integer -> Int -> Int -> ClientSession
95 newSession s ns un db ud pr = ClientSession
96 { sec = s
97 , nsec = ns
98 , username = un
99 , dbid = db
100 , uuid = ud
101 , prand = pr}