I want to add another condition which removes a user that has already liked a film

╄→尐↘猪︶ㄣ 提交于 2019-12-24 08:27:33

问题


I am trying to create a function which allows a user to dislike a film. However the user can only exist in the list of likes/dislikes but not both

 addUserDislikes :: Title -> User -> [Film] -> [Film] 
 addUserDislikes title user db = [ if ti == title && elem user dislike == False then (ti, di, yr,like,dislike++ [user])else (ti, di, yr, like, dislike) | (ti, di, yr, like, dislike) <- db] 

This function only adds the user to the list of Dislikes but does not remove it from list of likes how do I do this?

other info - The Title & User are Strings. Like and Dislikes are lists in the tuple Film.


回答1:


Trying to accomplish this in a list comprehension is hardly the easiest, or more readable approach. Instead, consider defining a function that handles a single Film. If you have such a function, the overall function becomes a simple map:

addUserDislikes :: Title -> User -> [Film] -> [Film]
addUserDislikes title user = fmap $ dislikeFilm title user

You can define dislikeFilm as a stand-alone function, if you will, or alternatively define it using let or where in addUserDislikes. If you write the function as a stand-alone function, you could write it like this:

dislikeFilm title user film@(ti, di, yr, likes, dislikes) =
  if ti == title
    then (ti, di, yr, delete user likes, user : dislikes)
    else film

Notice that this function returns film unmodified if title doesn't match. If, on the other hand, the title matches, it cons user onto dislikes, and simultaneously removes if from likes. For that, it uses delete from Data.List.

Here's some examples:

*Q49336125> addUserDislikes "2010" "foo" []
[]

*Q49336125> addUserDislikes "2010" "foo" [("2010", "Peter Hyams", 1984, [], [])]
[("2010","Peter Hyams",1984,[],["foo"])]

*Q49336125> addUserDislikes "2010" "foo" [("2010", "Peter Hyams", 1984, ["foo"], [])]
[("2010","Peter Hyams",1984,[],["foo"])]

*Q49336125> addUserDislikes "2010" "foo" [
    ("2010", "Peter Hyams", 1984, ["foo"], ["bar"]),
    ("2001", "Stanley Kubrick", 1968, ["baz", "qux"], [])]
[("2010","Peter Hyams",1984,[],["foo","bar"]),
 ("2001","Stanley Kubrick",1968,["baz","qux"],[])]

(Last evaluation hand-edited by me to make it more readable.)

(P.S. I liked both 2001 and 2010, but I wanted to use some short film titles.)



来源:https://stackoverflow.com/questions/49336125/i-want-to-add-another-condition-which-removes-a-user-that-has-already-liked-a-fi

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