Haskell:递归函数,只将部分学生放在列表中

时间:2018-03-17 22:42:27

标签: database haskell recursion

这是数据类型:

data Student = Student String Int [String] [String]
   deriving (Show,Read)

这是我的数据库:

db :: [Student]
db = [  
       Student "JenDavis" 54 ["Physics", "Maths"] ["Biology", "English"],
       Student "BenBlue" 62 ["Art", "English"] ["Maths", "PE"]          ,
       Student "JaydenBrimes" 56 ["Chemistry", "PE"] ["Music", "Maths"]
     ]

目前,如果学生姓名在学生数据中匹配,并且喜欢的主题不在列表中,则该功能将输入的主题添加到喜欢的主题列表中。然后它将数据库从那里返回到最后,而不是之前的任何数据。

仅将部分学生列入名单的功能:

likedNewSubject :: String -> String -> [Student] -> [Student]
likedNewSubject newSubject studName [] = []
likedNewSubject newSubject studName ((Student n g lk dl):students)
     | (n == studName) && (newSubject `notElem` lk) = (Student n g liked dl):students ++ likedNewSubject newSubject studName students
     | otherwise = likedNewSubject newSubject studName students
     where liked = newSubject:lk

如何使该功能将所有学生添加到数据库而不重复?

目前只有在我使用学生"JenDavis"时才有效。 如果“BenBlue”喜欢某个主题,则只返回"BenBlue""JaydenBrimes"的学生数据,而不是"JenDavis"。谢谢

我试过这个:

likedNewSubjectt :: String -> String -> [Student] -> [Student]
likedNewSubjectt newSubject studName [] = []
likedNewSubjectt newSubject studName ((Student n g lk dl):students)
    | (n == studName) && (newSubject `elem` lk) = (Student n g lk dl):students ++ likedNewSubjectt newSubject studName students
    | (n == studName) && (newSubject `notElem` lk) = (Student n g lk dl):students ++ likedNewSubjectt newSubject studName students
    | otherwise = likedNewSubjectt newSubject studName students
    where liked = newSubject:lk

做同样的事情

我试过这个:

likedNewSubjectt :: String -> String -> [Student] -> [Student]
likedNewSubjectt newSubject studName [] = []
likedNewSubjectt newSubject studName ((Student n g lk dl):students)
    | (n /= studName) = (Student n g lk dl):students ++ likedNewSubjectt newSubject studName students
dl):students ++ likedNewSubjectt newSubject studName students
    | (n == studName) && (newSubject `notElem` lk) = (Student n g lk dl):students ++ likedNewSubjectt newSubject studName students
    | otherwise = likedNewSubjectt newSubject studName students
    where liked = newSubject:lk

确实将所有内容放在列表中但有重复项,并且不会将喜欢的主题添加到列表中。

我觉得它应该是一个非常简单的解决方案,但我之前没有见过它,因此我不知道它是什么样的!我也尝试过使用

| (Student n g lk dl) `notElem` students = (Student n g lk dl):students

但它会发出Eq错误。我很感激。

likedNewSubject :: String -> String -> [Student] -> [Student] likedNewSubject newSubject studName [] = [] likedNewSubject newSubject studName ((Student n g lk dl):students) | (n == studName) && (newSubject {notElem {1}} {notElem {1}}

这是上述函数给出的eq误差。

eq error given after inputting code above

0 个答案:

没有答案