haskell,如何使用元组创建小型数据库
这是我的问题,我需要使用 2 元组(即对)列表构建一个数据库,表示有关拥有县和城市的一个国家的信息 例如,c1 拥有 c2,c2 拥有 c3,c3 拥有 c4,但没有直接说明 c1(等)对 c4 的“间接”所有权。 我需要编写一个函数“owns”,给定两个命名国家的字符串,返回一个布尔值,指示第一个字符串是否拥有第二个字符串(甚至是间接的,如上面的 c1 和 c4 的情况)。 这是我的代码,我知道它不太正确,我对 haskell 非常陌生......因此,需要帮助......
lst = [("uk","scotland"),("scotland","aberdeen"),("china","hongkong"),("hongkong","kulong")]
owns :: String-> String -> Bool
owns a b
| n = lookup a (fromList lst)
|if b==n
return true
|otherwise m = lookup n (fromlist lst)
if b==m
return true
| otherwise = False
我期望输出结果应该是这样的:
Main> owns "uk" "scotland"
True
Main> owns "uk" "aberdeen"
True
Main> owns "uk" "hongkong"
False
here s my question, i need to construct a database representing information about one country owning county owning city, using a list of 2-tuples (i.e., pairs)
for example c1 owns c2, which owns c3, which owns c4, but where the "indirect" ownership of c4 by c1 (etc.) is not directly stated.
i need to write a function 'owns' which, given two strings naming country returns a Boolean indicating whether the first owns the second (even indirectly, as with the case of c1 and c4 above).
here s my code, and i know it s not quite right, i new very new to haskell ....therefore, need help please....
lst = [("uk","scotland"),("scotland","aberdeen"),("china","hongkong"),("hongkong","kulong")]
owns :: String-> String -> Bool
owns a b
| n = lookup a (fromList lst)
|if b==n
return true
|otherwise m = lookup n (fromlist lst)
if b==m
return true
| otherwise = False
i m expecting the output result should be something like:
Main> owns "uk" "scotland"
True
Main> owns "uk" "aberdeen"
True
Main> owns "uk" "hongkong"
False
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会想知道这是如何工作的。
首先,我们认识到这是一个递归问题。 c1 拥有 c2 拥有 c3 拥有 c4 等等。我们不知道这可能需要多少步骤。所以我们需要一个基本情况和一个递归情况。
基本情况是
父==子
。如果这是真的,那么总体答案就是真的。现在,递归的情况。
any
接受一个函数和一个列表,如果列表中的任何成员使函数返回 True,则返回 True。(我现在需要睡觉,如果需要的话稍后会再回来。)
You will want to know how this works.
First, we recognise that this is a recursion question. c1 owns c2 owns c3 owns c4 etc. We don't know how many steps this could take. So we need a base case and a recursive case.
The base case is
parent == child
. If this is True, then the overall answer is True.Now, the recursive case.
any
takes a function and a list, and returns True if any member of the list makes the function return True.(I need to sleep now, will come back to this later if needed.)