我是 Haskell 的新手,在这种情况下需要一些帮助。我有以下 list
-- create a type for bank account
type AcNo = String
type Name = String
type City = String
type Amnt = Int
type AcInfo = [(AcNo, Name, City, Amnt)]
-- function to get the data of bank accounts to a list of tuples
bankAccounts :: AcInfo
bankAccounts = [("oo1", "Sahan", "Colomb", 100),("002", "John", "Jafna", 200)]
我的要求是获取账号对应的金额,比如001应该给100。
我写的函数是这样的
--Function to check the balance of a person
checkBalance :: bankAccounts -> AcNo -> Amnt
checkBalance dbase number = Amnt|(AcNo, Name, City, Amnt) <- dbase, AcNo==number}
第二行是我卡在那里给出错误信息的地方
输入中的语法错误(意外的“|”)
我想在这方面得到一些帮助。谢谢。
最佳答案
回想一下 Haskell 类型的名称以大写字母开头,因此 checkBalance
的类型应该是
checkBalance :: AcInfo -> AcNo -> Amnt
在您的问题中,您似乎旨在使用列表理解,但您的语法并不完全正确。
checkBalance dbase number = head [amnt | (acNo, name, city, amnt) <- dbase,
acNo == number]
如果帐户在
dbase
中,则此定义很好*Main> checkBalance bankAccounts "oo1" 100
but blows up when it isn't.
*Main> checkBalance bankAccounts "001" *** Exception: Prelude.head: empty list
A better type for checkBalance
is
checkBalance :: AcInfo -> AcNo -> Maybe Amnt
代表一般情况,即
dbase
可能包含也可能不包含 number
。
关于list - 从具有 2 个以上元素的元组列表中检索一个元素 (Haskell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6566866/