代码之家  ›  专栏  ›  技术社区  ›  Ethan Smallwood

Haskell从列表中的记录获取数据

  •  0
  • Ethan Smallwood  · 技术社区  · 2 年前

    我正在使用haskell和im尝试输出列表中记录的所有数据。但我不知道怎么做。 Image of code

    data Employee = Employee { name :: String,  
                               position :: String,
                               idNum :: Int 
                               } 
    
    samSmith = Employee {name = "Sam Smith", position = "Manager", idNum = 1000}
    pamMarx = Employee {name = "Pam Marx", position = "Sales", idNum = 1001}
    test = Employee {name = "Test", position = "test", idNum =0}
    test2 = Employee {name = "Test2", position = "test2", idNum =01}
    test3 = Employee {name = "Test3", position = "test3", idNum =20}
    test4 = Employee {name = "Test4", position = "test4", idNum =30}
    test5 = Employee {name = "Test5", position = "test5", idNum =40}
    
    testData = [samSmith,pamMarx,test,test2,test3,test4,test5]
    
    renderEmployee :: Employee -> (String,String,Int)
    renderEmployee re = (name re,position re,idNum re)
    
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   PCDSandwichMan    2 年前

    你能这样做吗?

    data Employee = Employee { name :: String,  
                               position :: String,
                               idNum :: Int 
                                } deriving (Show)
                                
    
    --  Generate a list of employees
    employees :: [Employee]
    employees = [Employee "John" "Manager" 1,
                 Employee "Mary" "Sales" 2,
                 Employee "Steve" "Sales" 3,
                 Employee "Joe" "Manager" 4,
                 Employee "Sally" "Sales" 5,
                 Employee "Mark" "Sales" 6,
                 Employee "Sally" "Manager" 7]
    
    -- Output the array of employees
    printEmployees :: [Employee] -> IO ()
    printEmployees [] = putStrLn "No employees"
    printEmployees (x:xs) = putStrLn (name x ++ " " ++ position x ++ " " ++ show (idNum x)) >> printEmployees xs