【问题标题】:Haskell: Adding an element to a list inside a data typeHaskell:将元素添加到数据类型内的列表中
【发布时间】:2021-05-17 23:43:15
【问题描述】:

我正在尝试实现一个函数,该函数将一个元素(一个类型)添加到此类型的列表中,并添加到现有创建的数据类型中。由于 Haskell 数据变量是不可变的,我知道你必须创建一个与第一个具有相同特征的新数据并添加到它上面,但我似乎可以让 ghci 编译我的程序并让它做我想做的事情完成。

这是我的代码和函数,它应该将联系人添加到我一直在尝试处理的现有联系人 addContact 的列表中:

type Model = String
type Serie = String
type SerialNumber = String
type Type= (Model, Serie)
data Car =      Car
                SerialNumber
                Type
                deriving (Show, Read) 
type PastCars= (Car, ChangeCause)
data ChangeCause = Broken | Contract deriving (Show, Eq, Read)
type Phone = (Extension, Number)
type Number = String
type Extension = String
type Person = (FirstName, LastName)
type FirstName = String
type LastName = String
type Contact = (Person, Phone)

data Owner  = Owner Car Phone [PastCars] [Contact]
--Getters

listPastSN [] = []
listPastSN ((p,e):xs) = (serialNumber p, e):listPastSN xs

serialNumber :: Car -> String
serialNumber (Car s _)= s

car :: Owner -> Car 
car (Owner c _ _ _ ) = c

phone :: Owner -> Phone 
phone (Owner _ p _ _ ) = p

pastCar :: Owner -> [PastCars]
pastCar (Owner _ _ p _ ) = p

contacts :: Owner -> [Contact]
contacts (Owner _ _ _ c) = c

addContact :: FirstName -> LastName -> Extension -> Number -> Owner -> Owner
addContact f l e n ow = Owner car(ow) phone(ow) pastCar(ow) contacts(ow) ++ (Contact ((f, l), (e, n)))

让我有这些数据变量

car1 = Car  "X234X" ("Honda", "Civic")
car2 = Car  "X233X" ("Mazda", "3")
person1 =  Person "Peter" "Mcleod"
owner1 = Owner car1 ("888" , "4144144") [(car2, Broken)] [(person1,("123", "1231231")) ]

我希望能够将另一个联系人添加到 owner1 的联系人列表中。

解决这个问题的正确方法是什么。围绕这类案例提出的 SO 和 LYAH 解决方案似乎没有帮助。

【问题讨论】:

    标签: list haskell types


    【解决方案1】:

    您的代码中有多个问题。 addContact 函数的固定版本:

    addContact f l e n ow = 
      Owner (car ow) (phone ow) (pastCar ow) $ (contacts ow) ++ [((f, l), (e, n))]
    
    • Contact 不是构造函数,它是类型别名。
    • f a(b)f a b 相同。所以Owner phone(x) 是相同的Owner phone x,同样适用于其他参数。
    • 看看(++) :: [a] -> [a] -> [a]的签名。你正在尝试,contacts(ow) ++ (Contact ((f, l), (e, n))
    • f a b ++ [1,2,3](f a b) ++ [1,2,3] 相同。你想要的是f a (b ++ [1,2,3])f a $ b ++ [1,2,3]

    【讨论】:

    • 感谢您的帮助,现在该命令的编译错误少了很多,但仍有一个错误,您知道是什么原因造成的吗?错误: • 无法将预期类型“Person”与实际类型“(FirstName, LastName)”匹配 • 在表达式中:(f, l) 在表达式中:((f, l), (e, n)) 在'(++)'的第二个参数,即'[((f, l), (e, n))]'
    • 这意味着你的代码与问题的代码不同。您将 Person 的声明从类型别名更改为数据声明,并且没有更新我给您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多