gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:15:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com