Last active
August 1, 2018 17:57
-
-
Save alastairparagas/4349c330285afb6048b3cdb756e7029b to your computer and use it in GitHub Desktop.
Pattern Matching in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Main where | |
| import Control.Monad.IO.Class (liftIO) | |
| import Control.Monad.Trans.Resource (runResourceT) | |
| import Data.Conduit (($$+-), ($=+), runConduit) | |
| import Data.Conduit.List (mapM_, map, filter, catMaybes) | |
| import Data.Text (unpack) | |
| import Data.Maybe (fromJust) | |
| import Web.Twitter.Types | |
| (StreamingAPI(SStatus, SRetweetedStatus) | |
| , Status(Status), statusText, statusLang | |
| , RetweetedStatus(RetweetedStatus), rsRetweetedStatus | |
| ) | |
| import Web.Twitter.Conduit.Stream (stream) | |
| -- Filters Twitter tweets that are written only in English | |
| filterEnglishTweets :: StreamingAPI -> Bool | |
| filterEnglishTweets tweet = | |
| let | |
| langIsEnglish (Status {statusLang=language}) = case language of | |
| Just "en" -> True | |
| _ -> False | |
| in case tweet of | |
| SStatus statusObj -> langIsEnglish statusObj | |
| SRetweetedStatus (RetweetedStatus {rsRetweetedStatus=statusObj}) -> | |
| langIsEnglish statusObj | |
| _ -> False | |
| -- Filters Twitter tweets that are original posts | |
| tweetParser :: StreamingAPI -> Maybe String | |
| tweetParser tweet = case tweet of | |
| SStatus (Status {statusText=status}) -> Just $ unpack status | |
| SRetweetedStatus (RetweetedStatus {rsRetweetedStatus=rstatus}) -> | |
| Just $ unpack $ statusText rstatus | |
| _ -> Nothing | |
| main :: IO () | |
| main = do | |
| -- a bunch of connection setup details to Twitter | |
| {- | |
| Imagine a stream/production line of continually incoming Twitter tweets | |
| out of this stream, non-English tweets are removed | |
| each remaining tweet then gets packaged into one of two forms | |
| - one for original tweets | |
| - one for non-original tweets (retweets and whatnot) | |
| We then only grab packaged forms of original tweets and display them! | |
| -} | |
| in runResourceT $ do | |
| stream <- stream twitterInfo connectionManager apiRequest | |
| stream $=+ | |
| Data.Conduit.List.filter filterEnglishTweets $=+ | |
| Data.Conduit.List.map tweetParser $=+ | |
| Data.Conduit.List.catMaybes $$+- | |
| Data.Conduit.List.mapM_ (liftIO . putStrLn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment