我(在帮助下)创建了这个有效的代码:
newtype Name = Name String deriving (Show)
newtype Age = Age Int deriving (Show)
newtype Weight = Weight Int deriving (Show)
newtype Person = Person (Name, Age, Weight) deriving (Show)
isAdult :: Person -> Bool
isAdult (Person(_, Age a, _)) = a > 18
但是,当我尝试创建一个更复杂的函数updateWeight时,会出现问题,允许用户从之前的值更改Person的权重。你能指出我哪里出错吗?
updateWeight :: Person -> Int -> Person
updateWeight (Person(_,_,Weight w) b = (Person(_,_,w+b))
答案 0 :(得分:3)
问题是您无法在表达式的右侧使用_
占位符。您必须通过未更改的值。此外,您必须再次使用w + b
包装Weight
的结果。这应该有效:
updateWeight :: Person -> Int -> Person
updateWeight (Person(n, a, Weight w) b = (Person(n, a, Weight (w + b)))
对于Person
类型,您可以使用record syntax删除传递未更改值的样板。