开发者

haskell, how to make a small database by using tuple

开发者 https://www.devze.com 2023-02-24 06:08 出处:网络
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)

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 -> Boo开发者_Go百科l
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


owns parent child = parent == child || any (owns parent) [p | (p, c) <- lst, c == child]

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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消