list - 从具有 2 个以上元素的元组列表中检索一个元素 (Haskell)

标签 list haskell list-comprehension tuples nested-lists

我是 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/

相关文章:

python - 删除多个元素而不更新到最后

python - 从 Python 列表中删除一些重复项

python - python中的数组过滤器?

python - 替换python中二维列表中的项目

haskell - 列表特有的非同质类型是什么?它是如何实现的?

c - withArray 与 newArray

haskell - 在 Haskell 中循环遍历 Monad

coffeescript - 从列表理解创建两个数组

python - 根据条件在任意嵌套列表中查找组合

python - 从Python文件中读取数据库