如何修改Haskell代码获取列表中所有用户的Twitter推文?
Great question! To modify your allTweets function to retrieve tweets for every user in the input list (instead of just the first one), we can use Haskell's traversal functions to sequence the IO actions and combine results correctly. Here's a clean, idiomatic solution:
Step 1: Extract a Single User Fetch Helper
First, let's separate the logic for fetching tweets for one user into a reusable helper function. This makes the code more readable and easier to maintain:
urldata2 :: String urldata2 = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" -- Helper to fetch tweets for a single user fetchUserTweets :: String -> IO (Either String [Tweets]) fetchUserTweets user = getWith authenticate (urldata2 ++ user) >>= getBody1
Step 2: Update allTweets to Traverse the User List
Now, we can use traverse to apply fetchUserTweets to every user in the list. traverse will handle sequencing all the IO actions, and if any fetch fails (returns Left), the entire result will be Left with that error. If all fetches succeed, we'll concatenate all the tweet lists into a single list of Tweets:
allTweets :: [String] -> IO (Either String [Tweets]) allTweets users = fmap (fmap concat) $ traverse fetchUserTweets users
How This Works:
traverse fetchUserTweets usersreturnsIO (Either String [[Tweets]]): It runs the fetch for each user, and if any fails, it short-circuits to return that error. If all succeed, it gives a list of tweet lists (one per user).fmap concatwraps around theEithervalue: If the result isRight tweetLists, it concatenates all the sublists into a single[Tweets]. If it'sLeft err, it leaves the error untouched.
Handling Partial Failures (Optional)
If you want to collect tweets from successful users even if some fetches fail (instead of failing entirely), you can use mapM and filter the results:
allTweetsPartial :: [String] -> IO [Tweets] allTweetsPartial users = do results <- mapM fetchUserTweets users let successful = concat [tweets | Right tweets <- results] return successful
This version ignores any failed fetches and returns only the tweets from users that were retrieved successfully.
内容的提问来源于stack exchange,提问作者Alexia Desouza

