基本的Haskell:函数的问题

时间:2013-10-04 10:28:50

标签: haskell

我再次提出另一个基本问题。我正在使用ghci。

我(在帮助下)创建了这个有效的代码:

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))

1 个答案:

答案 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删除传递未更改值的样板。