Haskell: how to compare tuples?

北城余情 提交于 2019-12-24 10:00:18

问题


I'm trying to make a tuple list store some information in a particular way. Such as scotland belongs to uk, england belongs to uk, etc. Then take two strings as arguments (String -> String -> Bool) to make something like:

Main> owns "china" "beijing"
True
Main> owns "uk" "beijing"
False

Here's my code:

lst = [("uk","scotland"),("uk","england"),("uk","wales"),("china","beijing"),("china","hongkong"),("china","shanghai")]

owns :: String -> String -> Bool
owns a b = [n|(a,b) <- lst, (n == a)] && [m|(a,b) <- lst, (m==b]

Thanks for helping.


回答1:


If I understood your question right, you build a table of relations. Then, you get a single relation and want to check, whether it is in this table? Just use elem. elem a b yields true, if and only if a is in b.




回答2:


Look for "association lists" in the Haskell list library, and the lookup function:

Prelude> lookup "china" ls
Just "beijing"

where lookup is implemented as:

lookup _key []          =  Nothing
lookup  key ((x,y):xys)
    | key == x          =  Just y
    | otherwise         =  lookup key xys

Once you can lookup an element via its key, you can then compare that against the expected value.




回答3:


Here is a definition for the owns function:

owns :: String -> String -> Bool
owns a b = (a,b) `elem` lst

To answer the title of your question, any two tuples of the same length can be compared if their elements can be compared. If you are familiar with type classes at this point,

(Eq a, Eq b) => Eq (a, b)
(Eq a, Eq b, Eq c) => Eq (a, b, c)
...


来源:https://stackoverflow.com/questions/5654850/haskell-how-to-compare-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!