You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Haskell代码获取列表中所有用户的Twitter推文?

Fetch Tweets for All Users in a List

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 users returns IO (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 concat wraps around the Either value: If the result is Right tweetLists, it concatenates all the sublists into a single [Tweets]. If it's Left 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:37:01