Home > Software design >  Update Data in Files in Haskell
Update Data in Files in Haskell

Time:07-18

i am learning about CRUD in haskell, but i get confuse to update data. so far this i have made, this is my data type

data ProjAdmin = RecordProjAdmin { projname :: String, animator :: String,
                             projstatus :: String} deriving (Show, Read)

this is data sample

thisData :: [ProjAdmin]
thisData = [RecordProjAdmin {projname = "SERIAL", animator = "jet juy", projstatus = "ongoing"},
           RecordProjAdmin {projname = "FIILER", animator = "jet juy", projstatus = "done"},
           RecordProjAdmin {projname = "RECYCLE-TVS", animator = "jet juy", projstatus = "done"}]

the logic here is, i want to change projname = "SERIAL" from "ongoing" status to "done", so next time i will set getLine input name "SERIAL". i still bit confuse to doing this either

filTering :: [ProjAdmin]->[ProjAdmin]
filTering = filter(\s-> projstatus s == "ongoing")

this is my main

main ::IO ()
main  = do
         let output = filTering thisData
         let changedata = map (\y -> if projstatus y=="ongoing" then projstatus y = "done" else projstatus y) output
         print changedata

if there's is any idea to create update function, i'll be so greatfull thank you so much, or is it possible to using monad transformer to doing this? or if you know post that already answer or web link please let me know

thank you before

CodePudding user response:

In Haskell all values are immutable, so to "update" some value you need to write a function that actually produces a new value based on the old one.

Here is an implementation of filtering :: [ProjAdmin]->[ProjAdmin] (if you really want this function to have this type):

filtering :: [ProjAdmin]->[ProjAdmin]
filtering inputs = map changeIfCond inputs

-- changes the value if its name is "SERIAL" and status is "ongoing"
changeIfCond :: ProjAdmin -> ProjAdmin
changeIfCond (RecordProjAdmin name anim status) =
    if name == "SERIAL" && status == "ongoing"
       then RecordProjAdmin name anim "done"
       else RecordProjAdmin name anim status

Of course, writing functions like these is tedious, so you might want to look on the "lenses" topic.

CodePudding user response:

You're pretty close! Here's a corrected version of the incorrect line:

let changedata = map (\y -> if projstatus y == "ongoing" then y { projstatus = "done" } else y) output

For your Googling pleasure, this is called "record update syntax".

  • Related