2013-10-04 81 views
0

我再次遇到了另一個基本問題。我正在使用ghci。基本Haskell:功能問題

我(的幫助)創造了這個工作代碼:

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,允許用戶改變一個人的體重從它的前值出現問題。然而。你能指出我出錯的地方嗎?

updateWeight :: Person -> Int -> Person 
updateWeight (Person(_,_,Weight w) b = (Person(_,_,w+b)) 
+1

你能接受昨天的答案嗎? :) –

回答

3

問題是,您不能在表達式的右側使用_佔位符。你必須通過未改變的值。此外,您必須再次將w + b的結果與Weight包裝在一起。這應該工作:

updateWeight :: Person -> Int -> Person 
updateWeight (Person(n, a, Weight w) b = (Person(n, a, Weight (w + b))) 

您可以通過使用record syntaxPerson類型擺脫穿過不變值的樣板。