-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Espial is an open-source, web-based bookmarking server. -- -- Espial is an open-source, web-based bookmarking server. - Yesod + -- PureScript + sqlite3 - multi-user (w/ privacy scopes) - tags, stars, -- editing, deleting @package espial @version 0.0.19 module Generic constrName :: (HasConstructor (Rep a), Generic a) => a -> String class HasConstructor (f :: Type -> Type) genericConstrName :: HasConstructor f => f x -> String instance Generic.HasConstructor f => Generic.HasConstructor (GHC.Generics.D1 c f) instance (Generic.HasConstructor x, Generic.HasConstructor y) => Generic.HasConstructor (x GHC.Generics.:+: y) instance GHC.Generics.Constructor c => Generic.HasConstructor (GHC.Generics.C1 c f) module ModelCustom mkSlug :: Int -> IO Text newtype BmSlug BmSlug :: Text -> BmSlug [unBmSlug] :: BmSlug -> Text mkBmSlug :: IO BmSlug newtype NtSlug NtSlug :: Text -> NtSlug [unNtSlug] :: NtSlug -> Text mkNtSlug :: IO NtSlug policy :: HashingPolicy newtype BCrypt BCrypt :: Text -> BCrypt [unBCrypt] :: BCrypt -> Text hashPassword :: Text -> IO BCrypt validatePasswordHash :: BCrypt -> Text -> Bool newtype ApiKey ApiKey :: Text -> ApiKey [unApiKey] :: ApiKey -> Text newtype HashedApiKey HashedApiKey :: Text -> HashedApiKey generateApiKey :: IO ApiKey hashApiKey :: ApiKey -> HashedApiKey instance Data.Aeson.Types.ToJSON.ToJSON ModelCustom.BmSlug instance Data.Aeson.Types.FromJSON.FromJSON ModelCustom.BmSlug instance GHC.Classes.Ord ModelCustom.BmSlug instance GHC.Read.Read ModelCustom.BmSlug instance GHC.Show.Show ModelCustom.BmSlug instance Database.Persist.Sql.Class.PersistFieldSql ModelCustom.BmSlug instance Database.Persist.Class.PersistField.PersistField ModelCustom.BmSlug instance GHC.Classes.Eq ModelCustom.BmSlug instance Data.Aeson.Types.ToJSON.ToJSON ModelCustom.NtSlug instance Data.Aeson.Types.FromJSON.FromJSON ModelCustom.NtSlug instance GHC.Classes.Ord ModelCustom.NtSlug instance GHC.Read.Read ModelCustom.NtSlug instance GHC.Show.Show ModelCustom.NtSlug instance Database.Persist.Sql.Class.PersistFieldSql ModelCustom.NtSlug instance Database.Persist.Class.PersistField.PersistField ModelCustom.NtSlug instance GHC.Classes.Eq ModelCustom.NtSlug instance Data.Aeson.Types.ToJSON.ToJSON ModelCustom.BCrypt instance Data.Aeson.Types.FromJSON.FromJSON ModelCustom.BCrypt instance GHC.Classes.Ord ModelCustom.BCrypt instance GHC.Show.Show ModelCustom.BCrypt instance Database.Persist.Sql.Class.PersistFieldSql ModelCustom.BCrypt instance Database.Persist.Class.PersistField.PersistField ModelCustom.BCrypt instance GHC.Classes.Eq ModelCustom.BCrypt instance Data.Aeson.Types.ToJSON.ToJSON ModelCustom.HashedApiKey instance Data.Aeson.Types.FromJSON.FromJSON ModelCustom.HashedApiKey instance Database.Persist.Sql.Class.PersistFieldSql ModelCustom.HashedApiKey instance Database.Persist.Class.PersistField.PersistField ModelCustom.HashedApiKey instance GHC.Show.Show ModelCustom.HashedApiKey instance GHC.Classes.Ord ModelCustom.HashedApiKey instance GHC.Classes.Eq ModelCustom.HashedApiKey module Pretty cpprint :: (MonadIO m, Show a) => a -> m () cprint :: (MonadIO m, Show a) => a -> m () pprint :: (MonadIO m, Show a) => a -> m () -- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. In -- addition, you can configure a number of different aspects of Yesod by -- overriding methods in the Yesod typeclass. That instance is declared -- in the Foundation.hs file. module Settings -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config -- files, theoretically even a database. data AppSettings AppSettings :: String -> SqliteConf -> Maybe Text -> HostPreference -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Text -> Maybe Text -> Bool -> Maybe Text -> Maybe Int -> Maybe Text -> Bool -> Bool -> AppSettings -- | Directory from which to serve static files. [appStaticDir] :: AppSettings -> String -- | Configuration settings for accessing the database. [appDatabaseConf] :: AppSettings -> SqliteConf -- | Base for all generated URLs. If Nothing, determined from the -- request headers. [appRoot] :: AppSettings -> Maybe Text -- | Host/interface the server should bind to. [appHost] :: AppSettings -> HostPreference -- | Port to listen on [appPort] :: AppSettings -> Int -- | Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. [appIpFromHeader] :: AppSettings -> Bool -- | Use detailed request logging system [appDetailedRequestLogging] :: AppSettings -> Bool -- | Should all log messages be displayed? [appShouldLogAll] :: AppSettings -> Bool -- | Use the reload version of templates [appReloadTemplates] :: AppSettings -> Bool -- | Assume that files in the static dir may change after compilation [appMutableStatic] :: AppSettings -> Bool -- | Perform no stylesheet/script combining [appSkipCombining] :: AppSettings -> Bool -- | Copyright text to appear in the footer of the page [appCopyright] :: AppSettings -> Text -- | Google Analytics code [appAnalytics] :: AppSettings -> Maybe Text -- | Indicate if auth dummy login should be enabled. [appAuthDummyLogin] :: AppSettings -> Bool -- | Socks proxy host to use when making archive requests [appArchiveSocksProxyHost] :: AppSettings -> Maybe Text -- | Socks proxy port to use when making archive requests [appArchiveSocksProxyPort] :: AppSettings -> Maybe Int -- | Uri to app source code [appSourceCodeUri] :: AppSettings -> Maybe Text [appSSLOnly] :: AppSettings -> Bool [appAllowNonHttpUrlSchemes] :: AppSettings -> Bool -- | Settings for widgetFile, such as which template languages to -- support and default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings -- | How static files should be combined. combineSettings :: CombineSettings widgetFile :: String -> Q Exp -- | Raw bytes at compile time of config/settings.yml configSettingsYmlBS :: ByteString -- | config/settings.yml, parsed to a Value. configSettingsYmlValue :: Value -- | A version of AppSettings parsed at compile time from -- config/settings.yml. compileTimeAppSettings :: AppSettings combineStylesheets :: Name -> [Route Static] -> Q Exp combineScripts :: Name -> [Route Static] -> Q Exp instance Data.Aeson.Types.FromJSON.FromJSON Settings.AppSettings module Settings.StaticFiles js_js_cookie_2_2_0_min_js_gz :: StaticRoute js_js_cookie_2_2_0_min_js :: StaticRoute js_html5shiv_min_js_gz :: StaticRoute js_html5shiv_min_js :: StaticRoute js_app_min_js_map_gz :: StaticRoute js_app_min_js_map :: StaticRoute js_app_min_js_gz :: StaticRoute js_app_min_js :: StaticRoute images_bluepin_gif :: StaticRoute css_tachyons_min_css_gz :: StaticRoute css_tachyons_min_css :: StaticRoute css_popup_css :: StaticRoute css_main_css :: StaticRoute module Types type DBM m a = MonadUnliftIO m => SqlPersistT m a type DB a = forall m. DBM m a type DBVal val = (PersistEntity val, PersistEntityBackend val ~ SqlBackend, PersistStore (PersistEntityBackend val)) module Model data User User :: !Text -> !BCrypt -> !Maybe HashedApiKey -> !Bool -> !Bool -> !Bool -> User [userName] :: User -> !Text [userPasswordHash] :: User -> !BCrypt [userApiToken] :: User -> !Maybe HashedApiKey [userPrivateDefault] :: User -> !Bool [userArchiveDefault] :: User -> !Bool [userPrivacyLock] :: User -> !Bool type UserId = Key User data Bookmark Bookmark :: !UserId -> !BmSlug -> !Text -> !Text -> !Text -> !UTCTime -> !Bool -> !Bool -> !Bool -> !Maybe Text -> Bookmark [bookmarkUserId] :: Bookmark -> !UserId [bookmarkSlug] :: Bookmark -> !BmSlug [bookmarkHref] :: Bookmark -> !Text [bookmarkDescription] :: Bookmark -> !Text [bookmarkExtended] :: Bookmark -> !Text [bookmarkTime] :: Bookmark -> !UTCTime [bookmarkShared] :: Bookmark -> !Bool [bookmarkToRead] :: Bookmark -> !Bool [bookmarkSelected] :: Bookmark -> !Bool [bookmarkArchiveHref] :: Bookmark -> !Maybe Text type BookmarkId = Key Bookmark data BookmarkTag BookmarkTag :: !UserId -> !Text -> !BookmarkId -> !Int -> BookmarkTag [bookmarkTagUserId] :: BookmarkTag -> !UserId [bookmarkTagTag] :: BookmarkTag -> !Text [bookmarkTagBookmarkId] :: BookmarkTag -> !BookmarkId [bookmarkTagSeq] :: BookmarkTag -> !Int type BookmarkTagId = Key BookmarkTag data Note Note :: !UserId -> !NtSlug -> !Int -> !Text -> !Text -> !Bool -> !Bool -> !UTCTime -> !UTCTime -> Note [noteUserId] :: Note -> !UserId [noteSlug] :: Note -> !NtSlug [noteLength] :: Note -> !Int [noteTitle] :: Note -> !Text [noteText] :: Note -> !Text [noteIsMarkdown] :: Note -> !Bool [noteShared] :: Note -> !Bool [noteCreated] :: Note -> !UTCTime [noteUpdated] :: Note -> !UTCTime type NoteId = Key Note migrateSchema :: Migration entityDefListFormigrateSchema :: [EntityDef] newtype UTCTimeStr UTCTimeStr :: UTCTime -> UTCTimeStr [unUTCTimeStr] :: UTCTimeStr -> UTCTime newtype UserNameP UserNameP :: Text -> UserNameP [unUserNameP] :: UserNameP -> Text newtype TagsP TagsP :: [Text] -> TagsP [unTagsP] :: TagsP -> [Text] data SharedP SharedAll :: SharedP SharedPublic :: SharedP SharedPrivate :: SharedP data FilterP FilterAll :: FilterP FilterUnread :: FilterP FilterUntagged :: FilterP FilterStarred :: FilterP FilterSingle :: BmSlug -> FilterP newtype UnreadOnly UnreadOnly :: Bool -> UnreadOnly [unUnreadOnly] :: UnreadOnly -> Bool type Limit = Int64 type Page = Int64 migrateAll :: Migration dumpMigration :: DB () runMigrations :: DB () toMigration :: [Text] -> Migration migrateIndexes :: Migration sqliteGroupConcat :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value Text) authenticatePassword :: Text -> Text -> DB (Maybe (Entity User)) getUserByName :: UserNameP -> DB (Maybe (Entity User)) getApiKeyUser :: ApiKey -> DB (Maybe (Entity User)) bookmarksTagsQuery :: Key User -> SharedP -> FilterP -> [Tag] -> Maybe Text -> Limit -> Page -> DB (Int, [(Entity Bookmark, Maybe Text)]) allUserBookmarks :: Key User -> DB [(Entity Bookmark, Text)] parseSearchQuery :: (Text -> SqlExpr (Value Bool)) -> Text -> Maybe (SqlQuery ()) parseTimeText :: (ParseTime t, MonadFail m, Alternative m) => Text -> m t withTags :: Key Bookmark -> DB [Entity BookmarkTag] getNote :: Key User -> NtSlug -> DB (Maybe (Entity Note)) getNoteList :: Key User -> Maybe Text -> SharedP -> Limit -> Page -> DB (Int, [Entity Note]) mkBookmarkTags :: Key User -> Key Bookmark -> [Tag] -> [BookmarkTag] fileBookmarkToBookmark :: UserId -> FileBookmark -> IO Bookmark bookmarkTofileBookmark :: Bookmark -> Text -> FileBookmark data FFBookmarkNode FFBookmarkNode :: Maybe [FFBookmarkNode] -> !POSIXTime -> !Text -> !Maybe Text -> !Int -> !Int -> !POSIXTime -> !Maybe Text -> !Text -> !Text -> !Int -> !Maybe Text -> FFBookmarkNode [firefoxBookmarkChildren] :: FFBookmarkNode -> Maybe [FFBookmarkNode] [firefoxBookmarkDateAdded] :: FFBookmarkNode -> !POSIXTime [firefoxBookmarkGuid] :: FFBookmarkNode -> !Text [firefoxBookmarkIconUri] :: FFBookmarkNode -> !Maybe Text [firefoxBookmarkId] :: FFBookmarkNode -> !Int [firefoxBookmarkIndex] :: FFBookmarkNode -> !Int [firefoxBookmarkLastModified] :: FFBookmarkNode -> !POSIXTime [firefoxBookmarkRoot] :: FFBookmarkNode -> !Maybe Text [firefoxBookmarkTitle] :: FFBookmarkNode -> !Text [firefoxBookmarkType] :: FFBookmarkNode -> !Text [firefoxBookmarkTypeCode] :: FFBookmarkNode -> !Int [firefoxBookmarkUri] :: FFBookmarkNode -> !Maybe Text firefoxBookmarkNodeToBookmark :: UserId -> FFBookmarkNode -> IO [Bookmark] insertFileBookmarks :: Key User -> FilePath -> DB (Either String Int) insertFFBookmarks :: Key User -> FilePath -> DB (Either String Int) readFileBookmarks :: MonadIO m => FilePath -> m (Either String [FileBookmark]) readFFBookmarks :: MonadIO m => FilePath -> m (Either String FFBookmarkNode) exportFileBookmarks :: Key User -> FilePath -> DB () getFileBookmarks :: Key User -> DB [FileBookmark] data TagCloudMode TagCloudModeTop :: Bool -> Int -> TagCloudMode TagCloudModeLowerBound :: Bool -> Int -> TagCloudMode TagCloudModeRelated :: Bool -> [Tag] -> TagCloudMode TagCloudModeNone :: TagCloudMode isExpanded :: TagCloudMode -> Bool type Tag = Text tagCountTop :: Key User -> Int -> DB [(Text, Int)] tagCountLowerBound :: Key User -> Int -> DB [(Text, Int)] tagCountRelated :: Key User -> [Tag] -> DB [(Text, Int)] fileNoteToNote :: UserId -> FileNote -> IO Note insertDirFileNotes :: Key User -> FilePath -> DB (Either String Int) data AccountSettingsForm AccountSettingsForm :: Bool -> Bool -> Bool -> AccountSettingsForm [_privateDefault] :: AccountSettingsForm -> Bool [_archiveDefault] :: AccountSettingsForm -> Bool [_privacyLock] :: AccountSettingsForm -> Bool toAccountSettingsForm :: User -> AccountSettingsForm updateUserFromAccountSettingsForm :: Key User -> AccountSettingsForm -> DB () data BookmarkForm BookmarkForm :: Text -> Maybe Text -> Maybe Textarea -> Maybe Text -> Maybe Bool -> Maybe Bool -> Maybe Int64 -> Maybe BmSlug -> Maybe Bool -> Maybe UTCTimeStr -> Maybe Text -> BookmarkForm [_url] :: BookmarkForm -> Text [_title] :: BookmarkForm -> Maybe Text [_description] :: BookmarkForm -> Maybe Textarea [_tags] :: BookmarkForm -> Maybe Text [_private] :: BookmarkForm -> Maybe Bool [_toread] :: BookmarkForm -> Maybe Bool [_bid] :: BookmarkForm -> Maybe Int64 [_slug] :: BookmarkForm -> Maybe BmSlug [_selected] :: BookmarkForm -> Maybe Bool [_time] :: BookmarkForm -> Maybe UTCTimeStr [_archiveUrl] :: BookmarkForm -> Maybe Text gDefaultFormOptions :: Options toBookmarkFormList :: [(Entity Bookmark, Maybe Text)] -> [BookmarkForm] _toBookmarkForm :: (Entity Bookmark, [Entity BookmarkTag]) -> BookmarkForm _toBookmarkForm' :: (Entity Bookmark, Maybe Text) -> BookmarkForm _toBookmark :: UserId -> BookmarkForm -> IO Bookmark fetchBookmarkByUrl :: Key User -> Maybe Text -> DB (Maybe (Entity Bookmark, [Entity BookmarkTag])) data UpsertResult a Created :: a -> UpsertResult a Updated :: a -> UpsertResult a Failed :: String -> UpsertResult a maybeUpsertResult :: UpsertResult a -> Maybe a upsertBookmark :: Key User -> Maybe (Key Bookmark) -> Bookmark -> [Text] -> DB (UpsertResult (Key Bookmark)) updateBookmarkArchiveUrl :: Key User -> Key Bookmark -> Maybe Text -> DB () upsertNote :: Key User -> Maybe (Key Note) -> Note -> DB (UpsertResult (Key Note)) data FileBookmark FileBookmark :: !Text -> !Text -> !Text -> !UTCTime -> !Bool -> !Bool -> !Maybe Bool -> !Maybe Text -> !Text -> FileBookmark [fileBookmarkHref] :: FileBookmark -> !Text [fileBookmarkDescription] :: FileBookmark -> !Text [fileBookmarkExtended] :: FileBookmark -> !Text [fileBookmarkTime] :: FileBookmark -> !UTCTime [fileBookmarkShared] :: FileBookmark -> !Bool [fileBookmarkToRead] :: FileBookmark -> !Bool [fileBookmarkSelected] :: FileBookmark -> !Maybe Bool [fileBookmarkArchiveHref] :: FileBookmark -> !Maybe Text [fileBookmarkTags] :: FileBookmark -> !Text boolFromYesNo :: Text -> Bool boolToYesNo :: Bool -> Text data FileNote FileNote :: !Text -> !Text -> !Text -> !Int -> !UTCTime -> !UTCTime -> FileNote [fileNoteId] :: FileNote -> !Text [fileNoteTitle] :: FileNote -> !Text [fileNoteText] :: FileNote -> !Text [fileNoteLength] :: FileNote -> !Int [fileNoteCreatedAt] :: FileNote -> !UTCTime [fileNoteUpdatedAt] :: FileNote -> !UTCTime readFileNoteTime :: MonadFail m => String -> m UTCTime showFileNoteTime :: UTCTime -> String instance GHC.Classes.Ord Model.User instance GHC.Classes.Eq Model.User instance GHC.Show.Show Model.User instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Key Model.User) instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Key Model.User) instance Database.Persist.Sql.Class.PersistFieldSql (Database.Persist.Class.PersistEntity.Key Model.User) instance Database.Persist.Class.PersistField.PersistField (Database.Persist.Class.PersistEntity.Key Model.User) instance Web.Internal.HttpApiData.FromHttpApiData (Database.Persist.Class.PersistEntity.Key Model.User) instance Web.Internal.HttpApiData.ToHttpApiData (Database.Persist.Class.PersistEntity.Key Model.User) instance Web.PathPieces.PathPiece (Database.Persist.Class.PersistEntity.Key Model.User) instance GHC.Classes.Ord (Database.Persist.Class.PersistEntity.Key Model.User) instance GHC.Classes.Eq (Database.Persist.Class.PersistEntity.Key Model.User) instance GHC.Read.Read (Database.Persist.Class.PersistEntity.Key Model.User) instance GHC.Show.Show (Database.Persist.Class.PersistEntity.Key Model.User) instance GHC.Classes.Ord Model.Bookmark instance GHC.Classes.Eq Model.Bookmark instance GHC.Show.Show Model.Bookmark instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Database.Persist.Sql.Class.PersistFieldSql (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Database.Persist.Class.PersistField.PersistField (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Web.Internal.HttpApiData.FromHttpApiData (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Web.Internal.HttpApiData.ToHttpApiData (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Web.PathPieces.PathPiece (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance GHC.Classes.Ord (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance GHC.Classes.Eq (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance GHC.Read.Read (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance GHC.Show.Show (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance GHC.Classes.Ord Model.BookmarkTag instance GHC.Classes.Eq Model.BookmarkTag instance GHC.Show.Show Model.BookmarkTag instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Database.Persist.Sql.Class.PersistFieldSql (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Database.Persist.Class.PersistField.PersistField (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Web.Internal.HttpApiData.FromHttpApiData (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Web.Internal.HttpApiData.ToHttpApiData (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Web.PathPieces.PathPiece (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance GHC.Classes.Ord (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance GHC.Classes.Eq (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance GHC.Read.Read (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance GHC.Show.Show (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance GHC.Classes.Ord Model.Note instance GHC.Classes.Eq Model.Note instance GHC.Show.Show Model.Note instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Key Model.Note) instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Key Model.Note) instance Database.Persist.Sql.Class.PersistFieldSql (Database.Persist.Class.PersistEntity.Key Model.Note) instance Database.Persist.Class.PersistField.PersistField (Database.Persist.Class.PersistEntity.Key Model.Note) instance Web.Internal.HttpApiData.FromHttpApiData (Database.Persist.Class.PersistEntity.Key Model.Note) instance Web.Internal.HttpApiData.ToHttpApiData (Database.Persist.Class.PersistEntity.Key Model.Note) instance Web.PathPieces.PathPiece (Database.Persist.Class.PersistEntity.Key Model.Note) instance GHC.Classes.Ord (Database.Persist.Class.PersistEntity.Key Model.Note) instance GHC.Classes.Eq (Database.Persist.Class.PersistEntity.Key Model.Note) instance GHC.Read.Read (Database.Persist.Class.PersistEntity.Key Model.Note) instance GHC.Show.Show (Database.Persist.Class.PersistEntity.Key Model.Note) instance Data.Aeson.Types.ToJSON.ToJSON Model.UTCTimeStr instance Data.Aeson.Types.FromJSON.FromJSON Model.UTCTimeStr instance GHC.Generics.Generic Model.UTCTimeStr instance GHC.Read.Read Model.UTCTimeStr instance GHC.Show.Show Model.UTCTimeStr instance GHC.Classes.Eq Model.UTCTimeStr instance GHC.Read.Read Model.UserNameP instance GHC.Show.Show Model.UserNameP instance GHC.Classes.Eq Model.UserNameP instance GHC.Read.Read Model.TagsP instance GHC.Show.Show Model.TagsP instance GHC.Classes.Eq Model.TagsP instance GHC.Read.Read Model.SharedP instance GHC.Show.Show Model.SharedP instance GHC.Classes.Eq Model.SharedP instance GHC.Read.Read Model.FilterP instance GHC.Show.Show Model.FilterP instance GHC.Classes.Eq Model.FilterP instance GHC.Read.Read Model.UnreadOnly instance GHC.Show.Show Model.UnreadOnly instance GHC.Classes.Eq Model.UnreadOnly instance GHC.Classes.Ord Model.FFBookmarkNode instance GHC.Classes.Eq Model.FFBookmarkNode instance GHC.Show.Show Model.FFBookmarkNode instance GHC.Generics.Generic Model.TagCloudMode instance GHC.Read.Read Model.TagCloudMode instance GHC.Classes.Eq Model.TagCloudMode instance GHC.Show.Show Model.TagCloudMode instance GHC.Generics.Generic Model.AccountSettingsForm instance GHC.Read.Read Model.AccountSettingsForm instance GHC.Classes.Eq Model.AccountSettingsForm instance GHC.Show.Show Model.AccountSettingsForm instance GHC.Generics.Generic Model.BookmarkForm instance GHC.Read.Read Model.BookmarkForm instance GHC.Classes.Eq Model.BookmarkForm instance GHC.Show.Show Model.BookmarkForm instance GHC.Base.Functor Model.UpsertResult instance GHC.Classes.Eq a => GHC.Classes.Eq (Model.UpsertResult a) instance GHC.Show.Show a => GHC.Show.Show (Model.UpsertResult a) instance GHC.Classes.Ord Model.FileBookmark instance GHC.Classes.Eq Model.FileBookmark instance GHC.Show.Show Model.FileBookmark instance GHC.Classes.Ord Model.FileNote instance GHC.Classes.Eq Model.FileNote instance GHC.Show.Show Model.FileNote instance Data.Aeson.Types.FromJSON.FromJSON Model.FileNote instance Data.Aeson.Types.ToJSON.ToJSON Model.FileNote instance Data.Aeson.Types.FromJSON.FromJSON Model.FileBookmark instance Data.Aeson.Types.ToJSON.ToJSON Model.FileBookmark instance Data.Aeson.Types.FromJSON.FromJSON Model.BookmarkForm instance Data.Aeson.Types.ToJSON.ToJSON Model.BookmarkForm instance Data.Aeson.Types.FromJSON.FromJSON Model.AccountSettingsForm instance Data.Aeson.Types.ToJSON.ToJSON Model.AccountSettingsForm instance Data.Aeson.Types.FromJSON.FromJSON Model.TagCloudMode instance Data.Aeson.Types.ToJSON.ToJSON Model.TagCloudMode instance Data.Aeson.Types.FromJSON.FromJSON Model.FFBookmarkNode instance Web.PathPieces.PathPiece Model.UTCTimeStr instance Database.Persist.Class.PersistEntity.PersistEntity Model.Note instance Database.Persist.Class.PersistField.PersistField Model.Note instance Database.Persist.Sql.Class.PersistFieldSql Model.Note instance Database.Persist.Class.PersistStore.ToBackendKey Database.Persist.SqlBackend.Internal.SqlBackend Model.Note instance Data.Aeson.Types.ToJSON.ToJSON Model.Note instance Data.Aeson.Types.FromJSON.FromJSON Model.Note instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Entity Model.Note) instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Entity Model.Note) instance (TypeError ...) => Database.Persist.Class.PersistUnique.OnlyOneUniqueKey Model.Note instance (TypeError ...) => Database.Persist.Class.PersistUnique.AtLeastOneUniqueKey Model.Note instance Database.Persist.Class.PersistEntity.SymbolToField "id" Model.Note (Database.Persist.Class.PersistEntity.Key Model.Note) instance Database.Persist.Class.PersistEntity.SymbolToField "userId" Model.Note Model.UserId instance Database.Persist.Class.PersistEntity.SymbolToField "slug" Model.Note ModelCustom.NtSlug instance Database.Persist.Class.PersistEntity.SymbolToField "length" Model.Note GHC.Types.Int instance Database.Persist.Class.PersistEntity.SymbolToField "title" Model.Note Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "text" Model.Note Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "isMarkdown" Model.Note GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "shared" Model.Note GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "created" Model.Note Data.Time.Clock.Internal.UTCTime.UTCTime instance Database.Persist.Class.PersistEntity.SymbolToField "updated" Model.Note Data.Time.Clock.Internal.UTCTime.UTCTime instance Database.Persist.Class.PersistEntity.SafeToInsert Model.Note instance Database.Persist.Class.PersistEntity.PersistEntity Model.BookmarkTag instance Database.Persist.Class.PersistField.PersistField Model.BookmarkTag instance Database.Persist.Sql.Class.PersistFieldSql Model.BookmarkTag instance Database.Persist.Class.PersistStore.ToBackendKey Database.Persist.SqlBackend.Internal.SqlBackend Model.BookmarkTag instance Data.Aeson.Types.ToJSON.ToJSON Model.BookmarkTag instance Data.Aeson.Types.FromJSON.FromJSON Model.BookmarkTag instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Entity Model.BookmarkTag) instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Entity Model.BookmarkTag) instance (TypeError ...) => Database.Persist.Class.PersistUnique.OnlyOneUniqueKey Model.BookmarkTag instance Database.Persist.Class.PersistUnique.AtLeastOneUniqueKey Model.BookmarkTag instance Database.Persist.Class.PersistEntity.SymbolToField "id" Model.BookmarkTag (Database.Persist.Class.PersistEntity.Key Model.BookmarkTag) instance Database.Persist.Class.PersistEntity.SymbolToField "userId" Model.BookmarkTag Model.UserId instance Database.Persist.Class.PersistEntity.SymbolToField "tag" Model.BookmarkTag Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "bookmarkId" Model.BookmarkTag Model.BookmarkId instance Database.Persist.Class.PersistEntity.SymbolToField "seq" Model.BookmarkTag GHC.Types.Int instance Database.Persist.Class.PersistEntity.SafeToInsert Model.BookmarkTag instance Database.Persist.Class.PersistEntity.PersistEntity Model.Bookmark instance Database.Persist.Class.PersistField.PersistField Model.Bookmark instance Database.Persist.Sql.Class.PersistFieldSql Model.Bookmark instance Database.Persist.Class.PersistStore.ToBackendKey Database.Persist.SqlBackend.Internal.SqlBackend Model.Bookmark instance Data.Aeson.Types.ToJSON.ToJSON Model.Bookmark instance Data.Aeson.Types.FromJSON.FromJSON Model.Bookmark instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Entity Model.Bookmark) instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Entity Model.Bookmark) instance (TypeError ...) => Database.Persist.Class.PersistUnique.OnlyOneUniqueKey Model.Bookmark instance Database.Persist.Class.PersistUnique.AtLeastOneUniqueKey Model.Bookmark instance Database.Persist.Class.PersistEntity.SymbolToField "id" Model.Bookmark (Database.Persist.Class.PersistEntity.Key Model.Bookmark) instance Database.Persist.Class.PersistEntity.SymbolToField "userId" Model.Bookmark Model.UserId instance Database.Persist.Class.PersistEntity.SymbolToField "slug" Model.Bookmark ModelCustom.BmSlug instance Database.Persist.Class.PersistEntity.SymbolToField "href" Model.Bookmark Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "description" Model.Bookmark Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "extended" Model.Bookmark Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "time" Model.Bookmark Data.Time.Clock.Internal.UTCTime.UTCTime instance Database.Persist.Class.PersistEntity.SymbolToField "shared" Model.Bookmark GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "toRead" Model.Bookmark GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "selected" Model.Bookmark GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "archiveHref" Model.Bookmark (GHC.Maybe.Maybe Data.Text.Internal.Text) instance Database.Persist.Class.PersistEntity.SafeToInsert Model.Bookmark instance Database.Persist.Class.PersistEntity.PersistEntity Model.User instance Database.Persist.Class.PersistField.PersistField Model.User instance Database.Persist.Sql.Class.PersistFieldSql Model.User instance Database.Persist.Class.PersistStore.ToBackendKey Database.Persist.SqlBackend.Internal.SqlBackend Model.User instance Data.Aeson.Types.ToJSON.ToJSON Model.User instance Data.Aeson.Types.FromJSON.FromJSON Model.User instance Data.Aeson.Types.ToJSON.ToJSON (Database.Persist.Class.PersistEntity.Entity Model.User) instance Data.Aeson.Types.FromJSON.FromJSON (Database.Persist.Class.PersistEntity.Entity Model.User) instance Database.Persist.Class.PersistUnique.OnlyOneUniqueKey Model.User instance Database.Persist.Class.PersistUnique.AtLeastOneUniqueKey Model.User instance Database.Persist.Class.PersistEntity.SymbolToField "id" Model.User (Database.Persist.Class.PersistEntity.Key Model.User) instance Database.Persist.Class.PersistEntity.SymbolToField "name" Model.User Data.Text.Internal.Text instance Database.Persist.Class.PersistEntity.SymbolToField "passwordHash" Model.User ModelCustom.BCrypt instance Database.Persist.Class.PersistEntity.SymbolToField "apiToken" Model.User (GHC.Maybe.Maybe ModelCustom.HashedApiKey) instance Database.Persist.Class.PersistEntity.SymbolToField "privateDefault" Model.User GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "archiveDefault" Model.User GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SymbolToField "privacyLock" Model.User GHC.Types.Bool instance Database.Persist.Class.PersistEntity.SafeToInsert Model.User module Import.NoFoundation -- | Consumes a stream of input values and produces a stream of output -- values, without producing a final result. -- -- Since 0.5.0 type Conduit i (m :: Type -> Type) o = ConduitT i o m () -- | The ability to run any monadic action m a as IO a. -- -- This is more precisely a natural transformation. We need to new -- datatype (instead of simply using a forall) due to lack of -- support in GHC for impredicative types. newtype () => UnliftIO (m :: Type -> Type) UnliftIO :: (forall a. () => m a -> IO a) -> UnliftIO (m :: Type -> Type) [unliftIO] :: UnliftIO (m :: Type -> Type) -> forall a. () => m a -> IO a -- | Define settings for a Yesod applications. All methods have intelligent -- defaults, and therefore no implementation is required. class RenderRoute site => Yesod site -- | An absolute URL to the root of the application. Do not include -- trailing slash. -- -- Default value: guessApproot. If you know your application root -- statically, it will be more efficient and more reliable to instead use -- ApprootStatic or ApprootMaster. If you do not need full -- absolute URLs, you can use ApprootRelative instead. -- -- Note: Prior to yesod-core 1.5, the default value was -- ApprootRelative. approot :: Yesod site => Approot site -- | allows the user to specify how exceptions are cought. by default all -- async exceptions are thrown and synchronous exceptions render a 500 -- page. To catch all exceptions (even async) to render a 500 page, set -- this to catchSyncOrAsync. Beware this may have negative effects -- with functions like timeout. catchHandlerExceptions :: (Yesod site, MonadUnliftIO m) => site -> m a -> (SomeException -> m a) -> m a -- | Output error response pages. -- -- Default value: defaultErrorHandler. errorHandler :: Yesod site => ErrorResponse -> HandlerFor site TypedContent -- | Applies some form of layout to the contents of a page. defaultLayout :: Yesod site => WidgetFor site () -> HandlerFor site Html -- | Override the rendering function for a particular URL and query string -- parameters. One use case for this is to offload static hosting to a -- different domain name to avoid sending cookies. -- -- For backward compatibility default implementation is in terms of -- urlRenderOverride, probably ineffective -- -- Since 1.4.23 urlParamRenderOverride :: Yesod site => site -> Route site -> [(Text, Text)] -> Maybe Builder -- | Determine if a request is authorized or not. -- -- Return Authorized if the request is authorized, -- Unauthorized a message if unauthorized. If authentication is -- required, return AuthenticationRequired. isAuthorized :: Yesod site => Route site -> Bool -> HandlerFor site AuthResult -- | Determines whether the current request is a write request. By default, -- this assumes you are following RESTful principles, and determines this -- from request method. In particular, all except the following request -- methods are considered write: GET HEAD OPTIONS TRACE. -- -- This function is used to determine if a request is authorized; see -- isAuthorized. isWriteRequest :: Yesod site => Route site -> HandlerFor site Bool -- | The default route for authentication. -- -- Used in particular by isAuthorized, but library users can do -- whatever they want with it. authRoute :: Yesod site => site -> Maybe (Route site) -- | A function used to clean up path segments. It returns Right -- with a clean path or Left with a new set of pieces the user -- should be redirected to. The default implementation enforces: -- -- -- -- Note that versions of Yesod prior to 0.7 used a different set of rules -- involing trailing slashes. cleanPath :: Yesod site => site -> [Text] -> Either [Text] [Text] -- | Builds an absolute URL by concatenating the application root with the -- pieces of a path and a query string, if any. Note that the pieces of -- the path have been previously cleaned up by cleanPath. joinPath :: Yesod site => site -> Text -> [Text] -> [(Text, Text)] -> Builder -- | This function is used to store some static content to be served as an -- external file. The most common case of this is stashing CSS and -- JavaScript content in an external file; the Yesod.Widget module -- uses this feature. -- -- The return value is Nothing if no storing was performed; this -- is the default implementation. A Just Left gives the -- absolute URL of the file, whereas a Just Right gives the -- type-safe URL. The former is necessary when you are serving the -- content outside the context of a Yesod application, such as via -- memcached. addStaticContent :: Yesod site => Text -> Text -> ByteString -> HandlerFor site (Maybe (Either Text (Route site, [(Text, Text)]))) -- | Maximum allowed length of the request body, in bytes. This method may -- be ignored if maximumContentLengthIO is overridden. -- -- If Nothing, no maximum is applied. -- -- Default: 2 megabytes. maximumContentLength :: Yesod site => site -> Maybe (Route site) -> Maybe Word64 -- | Maximum allowed length of the request body, in bytes. This is similar -- to maximumContentLength, but the result lives in IO. -- This allows you to dynamically change the maximum file size based on -- some external source like a database or an IORef. -- -- The default implementation uses maximumContentLength. Future -- version of yesod will remove maximumContentLength and use this -- method exclusively. maximumContentLengthIO :: Yesod site => site -> Maybe (Route site) -> IO (Maybe Word64) -- | Creates a Logger to use for log messages. -- -- Note that a common technique (endorsed by the scaffolding) is to -- create a Logger value and place it in your foundation -- datatype, and have this method return that already created value. That -- way, you can use that same Logger for printing messages -- during app initialization. -- -- Default: the defaultMakeLogger function. makeLogger :: Yesod site => site -> IO Logger -- | Send a message to the Logger provided by getLogger. -- -- Default: the defaultMessageLoggerSource function, using -- shouldLogIO to check whether we should log. messageLoggerSource :: Yesod site => site -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO () -- | Where to Load sripts from. We recommend the default value, -- BottomOfBody. jsLoader :: Yesod site => site -> ScriptLoadPosition site -- | Default attributes to put on the JavaScript script tag -- generated for julius files jsAttributes :: Yesod site => site -> [(Text, Text)] -- | Same as jsAttributes but allows you to run arbitrary Handler -- code -- -- This is useful if you need to add a randomised nonce value to the -- script tag generated by widgetFile. If this function is -- overridden then jsAttributes is ignored. jsAttributesHandler :: Yesod site => HandlerFor site [(Text, Text)] -- | Create a session backend. Returning Nothing disables sessions. -- If you'd like to change the way that the session cookies are created, -- take a look at customizeSessionCookies. -- -- Default: Uses clientsession with a 2 hour timeout. makeSessionBackend :: Yesod site => site -> IO (Maybe SessionBackend) -- | How to store uploaded files. -- -- Default: When the request body is greater than 50kb, store in a temp -- file. For chunked request bodies, store in a temp file. Otherwise, -- store in memory. fileUpload :: Yesod site => site -> RequestBodyLength -> FileUpload -- | Should we log the given log source/level combination. -- -- Default: the defaultShouldLogIO function. -- -- Since 1.2.4 shouldLogIO :: Yesod site => site -> LogSource -> LogLevel -> IO Bool -- | A Yesod middleware, which will wrap every handler function. This -- allows you to run code before and after a normal handler. -- -- Default: the defaultYesodMiddleware function. -- -- Since: 1.1.6 yesodMiddleware :: (Yesod site, ToTypedContent res) => HandlerFor site res -> HandlerFor site res -- | How to allocate an InternalState for each request. -- -- The default implementation is almost always what you want. However, if -- you know that you are never taking advantage of the -- MonadResource instance in your handler functions, setting -- this to a dummy implementation can provide a small optimization. Only -- do this if you really know what you're doing, otherwise you can turn -- safe code into a runtime error! -- -- Since 1.4.2 yesodWithInternalState :: Yesod site => site -> Maybe (Route site) -> (InternalState -> IO a) -> IO a -- | Convert a title and HTML snippet into a Widget. Used -- primarily for wrapping up error messages for better display. defaultMessageWidget :: Yesod site => Html -> HtmlUrl (Route site) -> WidgetFor site () -- | A String is a list of characters. String constants in Haskell -- are values of type String. -- -- See Data.List for operations on lists. type String = [Char] -- | RealWorld is deeply magical. It is primitive, but it is -- not unlifted (hence ptrArg). We never manipulate -- values of type RealWorld; it's only used in the type system, to -- parameterise State#. data RealWorld data () => Bool False :: Bool True :: Bool -- | The character type Char is an enumeration whose values -- represent Unicode (or equivalently ISO/IEC 10646) code points (i.e. -- characters, see http://www.unicode.org/ for details). This set -- extends the ISO 8859-1 (Latin-1) character set (the first 256 -- characters), which is itself an extension of the ASCII character set -- (the first 128 characters). A character literal in Haskell has type -- Char. -- -- To convert a Char to or from the corresponding Int value -- defined by Unicode, use toEnum and fromEnum from the -- Enum class respectively (or equivalently ord and -- chr). data () => Char -- | Double-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- double-precision type. data () => Double -- | Single-precision floating point numbers. It is desirable that this -- type be at least equal in range and precision to the IEEE -- single-precision type. data () => Float -- | A fixed-precision integer type with at least the range [-2^29 .. -- 2^29-1]. The exact range for a given implementation can be -- determined by using minBound and maxBound from the -- Bounded class. data () => Int -- | A Word is an unsigned integral type, with the same size as -- Int. data () => Word data () => Ordering LT :: Ordering EQ :: Ordering GT :: Ordering -- | The Maybe type encapsulates an optional value. A value of type -- Maybe a either contains a value of type a -- (represented as Just a), or it is empty (represented -- as Nothing). Using Maybe is a good way to deal with -- errors or exceptional cases without resorting to drastic measures such -- as error. -- -- The Maybe type is also a monad. It is a simple kind of error -- monad, where all errors are represented by Nothing. A richer -- error monad can be built using the Either type. data () => Maybe a Nothing :: Maybe a Just :: a -> Maybe a -- | Arbitrary precision integers. In contrast with fixed-size integral -- types such as Int, the Integer type represents the -- entire infinite range of integers. -- -- Integers are stored in a kind of sign-magnitude form, hence do not -- expect two's complement form when using bit operations. -- -- If the value is small (fit into an Int), IS constructor -- is used. Otherwise Integer and IN constructors are used -- to store a BigNat representing respectively the positive or the -- negative value magnitude. -- -- Invariant: Integer and IN are used iff value doesn't fit -- in IS data () => Integer -- | A value of type IO a is a computation which, when -- performed, does some I/O before returning a value of type a. -- -- There is really only one way to "perform" an I/O action: bind it to -- Main.main in your program. When your program is run, the I/O -- will be performed. It isn't possible to perform I/O from an arbitrary -- function, unless that function is itself in the IO monad and -- called at some point, directly or indirectly, from Main.main. -- -- IO is a monad, so IO actions can be combined using -- either the do-notation or the >> and >>= -- operations from the Monad class. data () => IO a -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Show is equivalent to -- --
--   instance (Show a) => Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d > app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d > up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   
-- -- Note that right-associativity of :^: is ignored. For example, -- -- class () => Show a -- | Convert a value to a readable String. -- -- showsPrec should satisfy the law -- --
--   showsPrec d x r ++ s  ==  showsPrec d x (r ++ s)
--   
-- -- Derived instances of Read and Show satisfy the -- following: -- -- -- -- That is, readsPrec parses the string produced by -- showsPrec, and delivers the value that showsPrec started -- with. showsPrec :: Show a => Int -> a -> ShowS -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | The method showList is provided to allow the programmer to give -- a specialised way of showing lists of values. For example, this is -- used by the predefined Show instance of the Char type, -- where values of type String should be shown in double quotes, -- rather than between square brackets. showList :: Show a => [a] -> ShowS -- | Uninhabited data type data () => Void -- | The class of monoids (types with an associative binary operation that -- has an identity). Instances should satisfy the following: -- -- -- -- You can alternatively define mconcat instead of mempty, -- in which case the laws are: -- -- -- -- The method names refer to the monoid of lists under concatenation, but -- there are many other instances. -- -- Some types can be viewed as a monoid in more than one way, e.g. both -- addition and multiplication on numbers. In such cases we often define -- newtypes and make those instances of Monoid, e.g. -- Sum and Product. -- -- NOTE: Semigroup is a superclass of Monoid since -- base-4.11.0.0. class Semigroup a => Monoid a -- | Identity of mappend -- --
--   >>> "Hello world" <> mempty
--   "Hello world"
--   
mempty :: Monoid a => a -- | An associative operation -- -- NOTE: This method is redundant and has the default -- implementation mappend = (<>) since -- base-4.11.0.0. Should it be implemented manually, since -- mappend is a synonym for (<>), it is expected that -- the two functions are defined the same way. In a future GHC release -- mappend will be removed from Monoid. mappend :: Monoid a => a -> a -> a -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. -- --
--   >>> mconcat ["Hello", " ", "Haskell", "!"]
--   "Hello Haskell!"
--   
mconcat :: Monoid a => [a] -> a -- | The class of semigroups (types with an associative binary operation). -- -- Instances should satisfy the following: -- -- -- -- You can alternatively define sconcat instead of -- (<>), in which case the laws are: -- -- class () => Semigroup a -- | An associative operation. -- --
--   >>> [1,2,3] <> [4,5,6]
--   [1,2,3,4,5,6]
--   
(<>) :: Semigroup a => a -> a -> a -- | Reduce a non-empty list with <> -- -- The default definition should be sufficient, but this can be -- overridden for efficiency. -- --
--   >>> import Data.List.NonEmpty (NonEmpty (..))
--   
--   >>> sconcat $ "Hello" :| [" ", "Haskell", "!"]
--   "Hello Haskell!"
--   
sconcat :: Semigroup a => NonEmpty a -> a -- | Repeat a value n times. -- -- Given that this works on a Semigroup it is allowed to fail if -- you request 0 or fewer repetitions, and the default definition will do -- so. -- -- By making this a member of the class, idempotent semigroups and -- monoids can upgrade this to execute in <math> by picking -- stimes = stimesIdempotent or stimes = -- stimesIdempotentMonoid respectively. -- --
--   >>> stimes 4 [1]
--   [1,1,1,1]
--   
stimes :: (Semigroup a, Integral b) => b -> a -> a infixr 6 <> -- | A functor with application, providing operations to -- -- -- -- A minimal complete definition must include implementations of -- pure and of either <*> or liftA2. If it -- defines both, then they must behave the same as their default -- definitions: -- --
--   (<*>) = liftA2 id
--   
-- --
--   liftA2 f x y = f <$> x <*> y
--   
-- -- Further, any definition must satisfy the following: -- -- -- -- The other methods have the following default definitions, which may be -- overridden with equivalent specialized implementations: -- -- -- -- As a consequence of these laws, the Functor instance for -- f will satisfy -- -- -- -- It may be useful to note that supposing -- --
--   forall x y. p (q x y) = f x . g y
--   
-- -- it follows from the above that -- --
--   liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v
--   
-- -- If f is also a Monad, it should satisfy -- -- -- -- (which implies that pure and <*> satisfy the -- applicative functor laws). class Functor f => Applicative (f :: Type -> Type) -- | Lift a value. pure :: Applicative f => a -> f a -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. -- --

Example

-- -- Used in combination with (<$>), -- (<*>) can be used to build a record. -- --
--   >>> data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
--   
-- --
--   >>> produceFoo :: Applicative f => f Foo
--   
-- --
--   >>> produceBar :: Applicative f => f Bar
--   
--   >>> produceBaz :: Applicative f => f Baz
--   
-- --
--   >>> mkState :: Applicative f => f MyState
--   
--   >>> mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
--   
(<*>) :: Applicative f => f (a -> b) -> f a -> f b -- | Lift a binary function to actions. -- -- Some functors support an implementation of liftA2 that is more -- efficient than the default one. In particular, if fmap is an -- expensive operation, it is likely better to use liftA2 than to -- fmap over the structure and then use <*>. -- -- This became a typeclass method in 4.10.0.0. Prior to that, it was a -- function defined in terms of <*> and fmap. -- --

Example

-- --
--   >>> liftA2 (,) (Just 3) (Just 5)
--   Just (3,5)
--   
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- | Sequence actions, discarding the value of the first argument. -- --

Examples

-- -- If used in conjunction with the Applicative instance for Maybe, -- you can chain Maybe computations, with a possible "early return" in -- case of Nothing. -- --
--   >>> Just 2 *> Just 3
--   Just 3
--   
-- --
--   >>> Nothing *> Just 3
--   Nothing
--   
-- -- Of course a more interesting use case would be to have effectful -- computations instead of just returning pure values. -- --
--   >>> import Data.Char
--   
--   >>> import Text.ParserCombinators.ReadP
--   
--   >>> let p = string "my name is " *> munch1 isAlpha <* eof
--   
--   >>> readP_to_S p "my name is Simon"
--   [("Simon","")]
--   
(*>) :: Applicative f => f a -> f b -> f b -- | Sequence actions, discarding the value of the second argument. (<*) :: Applicative f => f a -> f b -> f a infixl 4 <*> infixl 4 *> infixl 4 <* -- | A type f is a Functor if it provides a function fmap -- which, given any types a and b lets you apply any -- function from (a -> b) to turn an f a into an -- f b, preserving the structure of f. Furthermore -- f needs to adhere to the following: -- -- -- -- Note, that the second law follows from the free theorem of the type -- fmap and the first law, so you need only check that the former -- condition holds. See -- https://www.schoolofhaskell.com/user/edwardk/snippets/fmap or -- https://github.com/quchen/articles/blob/master/second_functor_law.md -- for an explanation. class () => Functor (f :: Type -> Type) -- | fmap is used to apply a function of type (a -> b) -- to a value of type f a, where f is a functor, to produce a -- value of type f b. Note that for any type constructor with -- more than one parameter (e.g., Either), only the last type -- parameter can be modified with fmap (e.g., b in -- `Either a b`). -- -- Some type constructors with two parameters or more have a -- Bifunctor instance that allows both the last and the -- penultimate parameters to be mapped over. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe String -- using show: -- --
--   >>> fmap show Nothing
--   Nothing
--   
--   >>> fmap show (Just 3)
--   Just "3"
--   
-- -- Convert from an Either Int Int to an Either Int -- String using show: -- --
--   >>> fmap show (Left 17)
--   Left 17
--   
--   >>> fmap show (Right 17)
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> fmap (*2) [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> fmap even (2,2)
--   (2,True)
--   
-- -- It may seem surprising that the function is only applied to the last -- element of the tuple compared to the list example above which applies -- it to every element in the list. To understand, remember that tuples -- are type constructors with multiple type parameters: a tuple of 3 -- elements (a,b,c) can also be written (,,) a b c and -- its Functor instance is defined for Functor ((,,) a -- b) (i.e., only the third parameter is free to be mapped over with -- fmap). -- -- It explains why fmap can be used with tuples containing -- values of different types as in the following example: -- --
--   >>> fmap even ("hello", 1.0, 4)
--   ("hello",1.0,True)
--   
fmap :: Functor f => (a -> b) -> f a -> f b -- | Replace all locations in the input with the same value. The default -- definition is fmap . const, but this may be -- overridden with a more efficient version. -- --

Examples

-- -- Perform a computation with Maybe and replace the result with a -- constant value if it is Just: -- --
--   >>> 'a' <$ Just 2
--   Just 'a'
--   
--   >>> 'a' <$ Nothing
--   Nothing
--   
(<$) :: Functor f => a -> f b -> f a infixl 4 <$ -- | The Monad class defines the basic operations over a -- monad, a concept from a branch of mathematics known as -- category theory. From the perspective of a Haskell programmer, -- however, it is best to think of a monad as an abstract datatype -- of actions. Haskell's do expressions provide a convenient -- syntax for writing monadic expressions. -- -- Instances of Monad should satisfy the following: -- -- -- -- Furthermore, the Monad and Applicative operations should -- relate as follows: -- -- -- -- The above laws imply: -- -- -- -- and that pure and (<*>) satisfy the applicative -- functor laws. -- -- The instances of Monad for lists, Maybe and IO -- defined in the Prelude satisfy these laws. class Applicative m => Monad (m :: Type -> Type) -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. -- -- 'as >>= bs' can be understood as the do -- expression -- --
--   do a <- as
--      bs a
--   
(>>=) :: Monad m => m a -> (a -> m b) -> m b -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. -- -- 'as >> bs' can be understood as the do -- expression -- --
--   do as
--      bs
--   
(>>) :: Monad m => m a -> m b -> m b -- | Inject a value into the monadic type. return :: Monad m => a -> m a infixl 1 >>= infixl 1 >> -- | Representable types of kind *. This class is derivable in GHC -- with the DeriveGeneric flag on. -- -- A Generic instance must satisfy the following laws: -- --
--   from . toid
--   to . fromid
--   
class () => Generic a -- | The Bounded class is used to name the upper and lower limits of -- a type. Ord is not a superclass of Bounded since types -- that are not totally ordered may also have upper and lower bounds. -- -- The Bounded class may be derived for any enumeration type; -- minBound is the first constructor listed in the data -- declaration and maxBound is the last. Bounded may also -- be derived for single-constructor datatypes whose constituent types -- are in Bounded. class () => Bounded a minBound :: Bounded a => a maxBound :: Bounded a => a -- | Class Enum defines operations on sequentially ordered types. -- -- The enumFrom... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of Enum may be derived for any enumeration type -- (types whose constructors have no fields). The nullary constructors -- are assumed to be numbered left-to-right by fromEnum from -- 0 through n-1. See Chapter 10 of the Haskell -- Report for more details. -- -- For any type that is an instance of class Bounded as well as -- Enum, the following should hold: -- -- -- --
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y >= fromEnum x = maxBound
--             | otherwise                = minBound
--   
class () => Enum a -- | the successor of a value. For numeric types, succ adds 1. succ :: Enum a => a -> a -- | the predecessor of a value. For numeric types, pred subtracts -- 1. pred :: Enum a => a -> a -- | Convert from an Int. toEnum :: Enum a => Int -> a -- | Convert to an Int. It is implementation-dependent what -- fromEnum returns when applied to a value that is too large to -- fit in an Int. fromEnum :: Enum a => a -> Int -- | Used in Haskell's translation of [n..] with [n..] = -- enumFrom n, a possible implementation being enumFrom n = n : -- enumFrom (succ n). For example: -- -- enumFrom :: Enum a => a -> [a] -- | Used in Haskell's translation of [n,n'..] with [n,n'..] = -- enumFromThen n n', a possible implementation being -- enumFromThen n n' = n : n' : worker (f x) (f x n'), -- worker s v = v : worker s (s v), x = fromEnum n' - -- fromEnum n and f n y | n > 0 = f (n - 1) (succ y) | n < -- 0 = f (n + 1) (pred y) | otherwise = y For example: -- -- enumFromThen :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n..m] with [n..m] = -- enumFromTo n m, a possible implementation being enumFromTo n -- m | n <= m = n : enumFromTo (succ n) m | otherwise = []. For -- example: -- -- enumFromTo :: Enum a => a -> a -> [a] -- | Used in Haskell's translation of [n,n'..m] with [n,n'..m] -- = enumFromThenTo n n' m, a possible implementation being -- enumFromThenTo n n' m = worker (f x) (c x) n m, x = -- fromEnum n' - fromEnum n, c x = bool (>=) ((x -- 0) f n y | n > 0 = f (n - 1) (succ y) | n < 0 = f (n + -- 1) (pred y) | otherwise = y and worker s c v m | c v m = v : -- worker s c (s v) m | otherwise = [] For example: -- -- enumFromThenTo :: Enum a => a -> a -> a -> [a] -- | Extracting components of fractions. class (Real a, Fractional a) => RealFrac a -- | The function properFraction takes a real fractional number -- x and returns a pair (n,f) such that x = -- n+f, and: -- -- -- -- The default definitions of the ceiling, floor, -- truncate and round functions are in terms of -- properFraction. properFraction :: (RealFrac a, Integral b) => a -> (b, a) -- | truncate x returns the integer nearest x -- between zero and x truncate :: (RealFrac a, Integral b) => a -> b -- | round x returns the nearest integer to x; the -- even integer if x is equidistant between two integers round :: (RealFrac a, Integral b) => a -> b -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b -- | Integral numbers, supporting integer division. -- -- The Haskell Report defines no laws for Integral. However, -- Integral instances are customarily expected to define a -- Euclidean domain and have the following properties for the -- div/mod and quot/rem pairs, given suitable -- Euclidean functions f and g: -- -- -- -- An example of a suitable Euclidean function, for Integer's -- instance, is abs. -- -- In addition, toInteger should be total, and fromInteger -- should be a left inverse for it, i.e. fromInteger (toInteger i) = -- i. class (Real a, Enum a) => Integral a -- | integer division truncated toward zero -- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. quot :: Integral a => a -> a -> a -- | integer remainder, satisfying -- --
--   (x `quot` y)*y + (x `rem` y) == x
--   
-- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. rem :: Integral a => a -> a -> a -- | integer division truncated toward negative infinity -- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. div :: Integral a => a -> a -> a -- | integer modulus, satisfying -- --
--   (x `div` y)*y + (x `mod` y) == x
--   
-- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. mod :: Integral a => a -> a -> a -- | simultaneous quot and rem -- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. quotRem :: Integral a => a -> a -> (a, a) -- | simultaneous div and mod -- -- WARNING: This function is partial (because it throws when 0 is passed -- as the divisor) for all the integer types in base. divMod :: Integral a => a -> a -> (a, a) -- | conversion to Integer toInteger :: Integral a => a -> Integer infixl 7 `quot` infixl 7 `rem` infixl 7 `div` infixl 7 `mod` -- | Parsing of Strings, producing values. -- -- Derived instances of Read make the following assumptions, which -- derived instances of Show obey: -- -- -- -- For example, given the declarations -- --
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   
-- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readsPrec d r =  readParen (d > app_prec)
--                            (\r -> [(Leaf m,t) |
--                                    ("Leaf",s) <- lex r,
--                                    (m,t) <- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d > up_prec)
--                            (\r -> [(u:^:v,w) |
--                                    (u,s) <- readsPrec (up_prec+1) r,
--                                    (":^:",t) <- lex s,
--                                    (v,w) <- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   
-- -- Note that right-associativity of :^: is unused. -- -- The derived instance in GHC is equivalent to -- --
--   instance (Read a) => Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" <- lexP
--                                    m <- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u <- step readPrec
--                                    Symbol ":^:" <- lexP
--                                    v <- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   
-- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
--   instance Read T where
--     readPrec     = ...
--     readListPrec = readListPrecDefault
--   
class () => Read a -- | The Ord class is used for totally ordered datatypes. -- -- Instances of Ord can be derived for any user-defined datatype -- whose constituent types are in Ord. The declared order of the -- constructors in the data declaration determines the ordering in -- derived Ord instances. The Ordering datatype allows a -- single comparison to determine the precise ordering of two objects. -- -- Ord, as defined by the Haskell report, implements a total order -- and has the following properties: -- -- -- -- The following operator interactions are expected to hold: -- --
    --
  1. x >= y = y <= x
  2. --
  3. x < y = x <= y && x /= y
  4. --
  5. x > y = y < x
  6. --
  7. x < y = compare x y == LT
  8. --
  9. x > y = compare x y == GT
  10. --
  11. x == y = compare x y == EQ
  12. --
  13. min x y == if x <= y then x else y = True
  14. --
  15. max x y == if x >= y then x else y = True
  16. --
-- -- Note that (7.) and (8.) do not require min and -- max to return either of their arguments. The result is merely -- required to equal one of the arguments in terms of (==). -- -- Minimal complete definition: either compare or <=. -- Using compare can be more efficient for complex types. class Eq a => Ord a compare :: Ord a => a -> a -> Ordering (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool max :: Ord a => a -> a -> a min :: Ord a => a -> a -> a infix 4 >= infix 4 < infix 4 <= infix 4 > -- | Arbitrary-precision rational numbers, represented as a ratio of two -- Integer values. A rational number may be constructed using the -- % operator. type Rational = Ratio Integer -- | Fractional numbers, supporting real division. -- -- The Haskell Report defines no laws for Fractional. However, -- (+) and (*) are customarily expected -- to define a division ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- Fractional implement a field. However, all instances in -- base do. class Num a => Fractional a -- | Fractional division. (/) :: Fractional a => a -> a -> a -- | Reciprocal fraction. recip :: Fractional a => a -> a -- | Conversion from a Rational (that is Ratio -- Integer). A floating literal stands for an application of -- fromRational to a value of type Rational, so such -- literals have type (Fractional a) => a. fromRational :: Fractional a => Rational -> a infixl 7 / -- | Real numbers. -- -- The Haskell report defines no laws for Real, however -- Real instances are customarily expected to adhere to the -- following law: -- -- class (Num a, Ord a) => Real a -- | the rational equivalent of its real argument with full precision toRational :: Real a => a -> Rational -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, instances -- are encouraged to follow these properties: -- -- -- -- Minimal complete definition: either == or /=. class () => Eq a (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool infix 4 == infix 4 /= -- | See examples in Control.Monad.Reader. Note, the partially -- applied function type (->) r is a simple reader monad. See -- the instance declaration below. class Monad m => MonadReader r (m :: Type -> Type) | m -> r -- | Retrieves the monad environment. ask :: MonadReader r m => m r -- | The reader monad transformer, which adds a read-only environment to -- the given monad. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. newtype () => ReaderT r (m :: Type -> Type) a ReaderT :: (r -> m a) -> ReaderT r (m :: Type -> Type) a [runReaderT] :: ReaderT r (m :: Type -> Type) a -> r -> m a -- | The parameterizable reader monad. -- -- Computations are functions of a shared environment. -- -- The return function ignores the environment, while -- >>= passes the inherited environment to both -- subcomputations. type Reader r = ReaderT r Identity -- | The Either type represents values with two possibilities: a -- value of type Either a b is either Left -- a or Right b. -- -- The Either type is sometimes used to represent a value which is -- either correct or an error; by convention, the Left constructor -- is used to hold an error value and the Right constructor is -- used to hold a correct value (mnemonic: "right" also means "correct"). -- --

Examples

-- -- The type Either String Int is the type -- of values which can be either a String or an Int. The -- Left constructor can be used only on Strings, and the -- Right constructor can be used only on Ints: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> s
--   Left "foo"
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> n
--   Right 3
--   
--   >>> :type s
--   s :: Either String Int
--   
--   >>> :type n
--   n :: Either String Int
--   
-- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> fmap (*2) s
--   Left "foo"
--   
--   >>> fmap (*2) n
--   Right 6
--   
-- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
--   >>> import Data.Char ( digitToInt, isDigit )
--   
--   >>> :{
--       let parseEither :: Char -> Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   >>> :}
--   
-- -- The following should work, since both '1' and '2' -- can be parsed as Ints. -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither '1'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Right 3
--   
-- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
--   >>> :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x <- parseEither 'm'
--             y <- parseEither '2'
--             return (x + y)
--   
--   >>> :}
--   
-- --
--   >>> parseMultiple
--   Left "parse error"
--   
data () => Either a b Left :: a -> Either a b Right :: b -> Either a b -- | A type that can be converted from JSON, with the possibility of -- failure. -- -- In many cases, you can get the compiler to generate parsing code for -- you (see below). To begin, let's cover writing an instance by hand. -- -- There are various reasons a conversion could fail. For example, an -- Object could be missing a required key, an Array could -- be of the wrong size, or a value could be of an incompatible type. -- -- The basic ways to signal a failed conversion are as follows: -- -- -- -- prependFailure (or modifyFailure) add more information -- to a parser's error messages. -- -- An example type and instance using typeMismatch and -- prependFailure: -- --
--   -- Allow ourselves to write Text literals.
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   data Coord = Coord { x :: Double, y :: Double }
--   
--   instance FromJSON Coord where
--       parseJSON (Object v) = Coord
--           <$> v .: "x"
--           <*> v .: "y"
--   
--       -- We do not expect a non-Object value here.
--       -- We could use empty to fail, but typeMismatch
--       -- gives a much more informative error message.
--       parseJSON invalid    =
--           prependFailure "parsing Coord failed, "
--               (typeMismatch "Object" invalid)
--   
-- -- For this common case of only being concerned with a single type of -- JSON value, the functions withObject, withScientific, -- etc. are provided. Their use is to be preferred when possible, since -- they are more terse. Using withObject, we can rewrite the above -- instance (assuming the same language extension and data type) as: -- --
--   instance FromJSON Coord where
--       parseJSON = withObject "Coord" $ \v -> Coord
--           <$> v .: "x"
--           <*> v .: "y"
--   
-- -- Instead of manually writing your FromJSON instance, there are -- two options to do it automatically: -- -- -- -- To use the second, simply add a deriving Generic -- clause to your datatype and declare a FromJSON instance for -- your datatype without giving a definition for parseJSON. -- -- For example, the previous example can be simplified to just: -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics
--   
--   data Coord = Coord { x :: Double, y :: Double } deriving Generic
--   
--   instance FromJSON Coord
--   
-- -- or using the DerivingVia extension -- --
--   deriving via Generically Coord instance FromJSON Coord
--   
-- -- The default implementation will be equivalent to parseJSON = -- genericParseJSON defaultOptions; if you need -- different options, you can customize the generic decoding by defining: -- --
--   customOptions = defaultOptions
--                   { fieldLabelModifier = map toUpper
--                   }
--   
--   instance FromJSON Coord where
--       parseJSON = genericParseJSON customOptions
--   
class () => FromJSON a parseJSON :: FromJSON a => Value -> Parser a parseJSONList :: FromJSON a => Value -> Parser [a] -- | Default value for optional fields. Used by (.:?=) -- operator, and Generics and TH deriving with -- allowOmittedFields = True (default). omittedField :: FromJSON a => Maybe a -- | A space-efficient representation of a Word8 vector, supporting -- many efficient operations. -- -- A ByteString contains 8-bit bytes, or by using the operations -- from Data.ByteString.Char8 it can be interpreted as containing -- 8-bit characters. data () => ByteString -- | Persistent serialized Haskell records to the database. A Database -- Entity (A row in SQL, a document in MongoDB, etc) corresponds -- to a Key plus a Haskell record. -- -- For every Haskell record type stored in the database there is a -- corresponding PersistEntity instance. An instance of -- PersistEntity contains meta-data for the record. PersistEntity also -- helps abstract over different record types. That way the same query -- interface can return a PersistEntity, with each query returning -- different types of Haskell records. -- -- Some advanced type system capabilities are used to make this process -- type-safe. Persistent users usually don't need to understand the class -- associated data and functions. class (PersistField Key record, ToJSON Key record, FromJSON Key record, Show Key record, Read Key record, Eq Key record, Ord Key record) => PersistEntity record where { -- | Persistent allows multiple different backends (databases). type family PersistEntityBackend record; -- | By default, a backend will automatically generate the key Instead you -- can specify a Primary key made up of unique values. data family Key record; -- | An EntityField is parameterised by the Haskell record it -- belongs to and the additional type of that field. -- -- As of persistent-2.11.0.0, it's possible to use the -- OverloadedLabels language extension to refer to -- EntityField values polymorphically. See the documentation on -- SymbolToField for more information. data family EntityField record :: Type -> Type; -- | Unique keys besides the Key. data family Unique record; } -- | A lower-level key operation. keyToValues :: PersistEntity record => Key record -> [PersistValue] -- | A lower-level key operation. keyFromValues :: PersistEntity record => [PersistValue] -> Either Text (Key record) -- | A meta-operation to retrieve the Key EntityField. persistIdField :: PersistEntity record => EntityField record (Key record) -- | Retrieve the EntityDef meta-data for the record. entityDef :: PersistEntity record => proxy record -> EntityDef -- | Return meta-data for a given EntityField. persistFieldDef :: PersistEntity record => EntityField record typ -> FieldDef -- | A meta-operation to get the database fields of a record. toPersistFields :: PersistEntity record => record -> [PersistValue] -- | A lower-level operation to convert from database values to a Haskell -- record. fromPersistValues :: PersistEntity record => [PersistValue] -> Either Text record -- | This function allows you to build an Entity a by -- specifying an action that returns a value for the field in the -- callback function. Let's look at an example. -- --
--   parseFromEnvironmentVariables :: IO (Entity User)
--   parseFromEnvironmentVariables =
--       tabulateEntityA $ \userField ->
--           case userField of
--               UserName ->
--                   getEnv USER_NAME
--               UserAge -> do
--                   ageVar <- getEnv USER_AGE
--                   case readMaybe ageVar of
--                       Just age ->
--                           pure age
--                       Nothing ->
--                           error $ "Failed to parse Age from: " <> ageVar
--               UserAddressId -> do
--                   addressVar <- getEnv USER_ADDRESS_ID
--                   pure $ AddressKey addressVar
--   
tabulateEntityA :: (PersistEntity record, Applicative f) => (forall a. () => EntityField record a -> f a) -> f (Entity record) -- | A meta operation to retrieve all the Unique keys. persistUniqueKeys :: PersistEntity record => record -> [Unique record] -- | A lower level operation. persistUniqueToFieldNames :: PersistEntity record => Unique record -> NonEmpty (FieldNameHS, FieldNameDB) -- | A lower level operation. persistUniqueToValues :: PersistEntity record => Unique record -> [PersistValue] -- | Use a PersistField as a lens. fieldLens :: PersistEntity record => EntityField record field -> forall (f :: Type -> Type). Functor f => (field -> f field) -> Entity record -> f (Entity record) -- | Extract a Key record from a record value. -- Currently, this is only defined for entities using the -- Primary syntax for natural/composite keys. In a future -- version of persistent which incorporates the ID directly into -- the entity, this will always be Just. keyFromRecordM :: PersistEntity record => Maybe (record -> Key record) -- | By default, a backend will automatically generate the key Instead you -- can specify a Primary key made up of unique values. data family Key record -- | A JSON value represented as a Haskell value. data () => Value Object :: !Object -> Value Array :: !Array -> Value String :: !Text -> Value Number :: !Scientific -> Value Bool :: !Bool -> Value Null :: Value -- | SemiSequence was created to share code between -- IsSequence and NonNull. -- -- Semi means SemiGroup A SemiSequence can -- accomodate a SemiGroup such as NonEmpty or -- NonNull A Monoid should be able to fill out -- IsSequence. -- -- SemiSequence operations maintain the same type because they all -- maintain the same number of elements or increase them. However, a -- decreasing function such as filter may change they type. For example, -- from NonEmpty to '[]' This type-changing function exists on -- NonNull as nfilter -- -- filter and other such functions are placed in IsSequence -- -- NOTE: Like GrowingAppend, ideally we'd have a -- Semigroup superclass constraint here, but that would pull in -- more dependencies to this package than desired. class (Integral Index seq, GrowingAppend seq) => SemiSequence seq where { -- | The type of the index of a sequence. type family Index seq; } -- | intersperse takes an element and intersperses that element -- between the elements of the sequence. -- --
--   > intersperse ',' "abcde"
--   "a,b,c,d,e"
--   
intersperse :: SemiSequence seq => Element seq -> seq -> seq -- | Reverse a sequence -- --
--   > reverse "hello world"
--   "dlrow olleh"
--   
reverse :: SemiSequence seq => seq -> seq -- | find takes a predicate and a sequence and returns the first -- element in the sequence matching the predicate, or Nothing if -- there isn't an element that matches the predicate. -- --
--   > find (== 5) [1 .. 10]
--   Just 5
--   
--   > find (== 15) [1 .. 10]
--   Nothing
--   
find :: SemiSequence seq => (Element seq -> Bool) -> seq -> Maybe (Element seq) -- | Sort a sequence using an supplied element ordering function. -- --
--   > let compare' x y = case compare x y of LT -> GT; EQ -> EQ; GT -> LT
--   > sortBy compare' [5,3,6,1,2,4]
--   [6,5,4,3,2,1]
--   
sortBy :: SemiSequence seq => (Element seq -> Element seq -> Ordering) -> seq -> seq -- | Prepend an element onto a sequence. -- --
--   > 4 `cons` [1,2,3]
--   [4,1,2,3]
--   
cons :: SemiSequence seq => Element seq -> seq -> seq -- | Append an element onto a sequence. -- --
--   > [1,2,3] `snoc` 4
--   [1,2,3,4]
--   
snoc :: SemiSequence seq => seq -> Element seq -> seq -- | The type of the index of a sequence. type family Index seq -- | A type that can be converted to JSON. -- -- Instances in general must specify toJSON and -- should (but don't need to) specify toEncoding. -- -- An example type and instance: -- --
--   -- Allow ourselves to write Text literals.
--   {-# LANGUAGE OverloadedStrings #-}
--   
--   data Coord = Coord { x :: Double, y :: Double }
--   
--   instance ToJSON Coord where
--     toJSON (Coord x y) = object ["x" .= x, "y" .= y]
--   
--     toEncoding (Coord x y) = pairs ("x" .= x <> "y" .= y)
--   
-- -- Instead of manually writing your ToJSON instance, there are two -- options to do it automatically: -- -- -- -- To use the second, simply add a deriving Generic -- clause to your datatype and declare a ToJSON instance. If you -- require nothing other than defaultOptions, it is sufficient to -- write (and this is the only alternative where the default -- toJSON implementation is sufficient): -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics
--   
--   data Coord = Coord { x :: Double, y :: Double } deriving Generic
--   
--   instance ToJSON Coord where
--       toEncoding = genericToEncoding defaultOptions
--   
-- -- or more conveniently using the DerivingVia extension -- --
--   deriving via Generically Coord instance ToJSON Coord
--   
-- -- If on the other hand you wish to customize the generic decoding, you -- have to implement both methods: -- --
--   customOptions = defaultOptions
--                   { fieldLabelModifier = map toUpper
--                   }
--   
--   instance ToJSON Coord where
--       toJSON     = genericToJSON customOptions
--       toEncoding = genericToEncoding customOptions
--   
-- -- Previous versions of this library only had the toJSON method. -- Adding toEncoding had two reasons: -- --
    --
  1. toEncoding is more efficient for the common case that the -- output of toJSON is directly serialized to a -- ByteString. Further, expressing either method in terms of the -- other would be non-optimal.
  2. --
  3. The choice of defaults allows a smooth transition for existing -- users: Existing instances that do not define toEncoding still -- compile and have the correct semantics. This is ensured by making the -- default implementation of toEncoding use toJSON. This -- produces correct results, but since it performs an intermediate -- conversion to a Value, it will be less efficient than directly -- emitting an Encoding. (this also means that specifying nothing -- more than instance ToJSON Coord would be sufficient as a -- generically decoding instance, but there probably exists no good -- reason to not specify toEncoding in new instances.)
  4. --
class () => ToJSON a -- | Convert a Haskell value to a JSON-friendly intermediate type. toJSON :: ToJSON a => a -> Value -- | Encode a Haskell value as JSON. -- -- The default implementation of this method creates an intermediate -- Value using toJSON. This provides source-level -- compatibility for people upgrading from older versions of this -- library, but obviously offers no performance advantage. -- -- To benefit from direct encoding, you must provide an -- implementation for this method. The easiest way to do so is by having -- your types implement Generic using the DeriveGeneric -- extension, and then have GHC generate a method body as follows. -- --
--   instance ToJSON Coord where
--       toEncoding = genericToEncoding defaultOptions
--   
toEncoding :: ToJSON a => a -> Encoding toJSONList :: ToJSON a => [a] -> Value toEncodingList :: ToJSON a => [a] -> Encoding -- | Defines when it is acceptable to omit a field of this type from a -- record. Used by (.?=) operator, and Generics and TH -- deriving with omitNothingFields = True. omitField :: ToJSON a => a -> Bool -- | A map from keys to values. A map cannot contain duplicate keys; each -- key can map to at most one value. data () => HashMap k v -- | A Map from keys k to values a. -- -- The Semigroup operation for Map is union, which -- prefers values from the left operand. If m1 maps a key -- k to a value a1, and m2 maps the same key -- to a different value a2, then their union m1 <> -- m2 maps k to a1. data () => Map k a -- | 8-bit unsigned integer type data () => Word8 -- | 64-bit unsigned integer type data () => Word64 -- | 32-bit unsigned integer type data () => Word32 -- | 32-bit signed integer type data () => Int32 -- | 64-bit signed integer type data () => Int64 -- | The class Typeable allows a concrete representation of a type -- to be calculated. class () => Typeable (a :: k) -- | Class for string-like datastructures; used by the overloaded string -- extension (-XOverloadedStrings in GHC). class () => IsString a fromString :: IsString a => String -> a -- | A space efficient, packed, unboxed Unicode text type. data () => Text -- | A monoid on applicative functors. -- -- If defined, some and many should be the least solutions -- of the equations: -- -- class Applicative f => Alternative (f :: Type -> Type) -- | The identity of <|> empty :: Alternative f => f a -- | An associative binary operation (<|>) :: Alternative f => f a -> f a -> f a -- | One or more. some :: Alternative f => f a -> f [a] -- | Zero or more. many :: Alternative f => f a -> f [a] infixl 3 <|> -- | Define a HTTP proxy, consisting of a hostname and port number. data () => Proxy Proxy :: ByteString -> Int -> Proxy -- | The host name of the HTTP proxy in URI format. IPv6 addresses in -- square brackets. [proxyHost] :: Proxy -> ByteString -- | The port number of the HTTP proxy. [proxyPort] :: Proxy -> Int -- | This is the simplest representation of UTC. It consists of the day -- number, and a time offset from midnight. Note that if a day has a leap -- second added to it, it will have 86401 seconds. data () => UTCTime UTCTime :: Day -> DiffTime -> UTCTime -- | the day [utctDay] :: UTCTime -> Day -- | the time from midnight, 0 <= t < 86401s (because of -- leap-seconds) [utctDayTime] :: UTCTime -> DiffTime -- | Boxed vectors, supporting efficient slicing. data () => Vector a -- | Since 0.1.0.0 class Monoid builder => Builder builder lazy | builder -> lazy, lazy -> builder -- | Since 0.1.0.0 builderToLazy :: Builder builder lazy => builder -> lazy -- | Since 0.1.0.0 flushBuilder :: Builder builder lazy => builder -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: hashWithSalt. -- -- Note: the hash is not guaranteed to be stable across library -- versions, operating systems or architectures. For stable hashing use -- named hashes: SHA256, CRC32 etc. -- -- If you are looking for Hashable instance in time -- package, check time-compat class Eq a => Hashable a -- | Return a hash value for the argument, using the given salt. -- -- The general contract of hashWithSalt is: -- -- hashWithSalt :: Hashable a => Int -> a -> Int -- | Like hashWithSalt, but no salt is used. The default -- implementation uses hashWithSalt with some default salt. -- Instances might want to implement this method to provide a more -- efficient implementation than the default implementation. hash :: Hashable a => a -> Int infixl 0 `hashWithSalt` -- | The Foldable class represents data structures that can be reduced to a -- summary value one element at a time. Strict left-associative folds are -- a good fit for space-efficient reduction, while lazy right-associative -- folds are a good fit for corecursive iteration, or for folds that -- short-circuit after processing an initial subsequence of the -- structure's elements. -- -- Instances can be derived automatically by enabling the -- DeriveFoldable extension. For example, a derived instance for -- a binary tree might be: -- --
--   {-# LANGUAGE DeriveFoldable #-}
--   data Tree a = Empty
--               | Leaf a
--               | Node (Tree a) a (Tree a)
--       deriving Foldable
--   
-- -- A more detailed description can be found in the Overview -- section of Data.Foldable#overview. -- -- For the class laws see the Laws section of -- Data.Foldable#laws. class () => Foldable (t :: Type -> Type) -- | Monads that also support choice and failure. class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) -- | The identity of mplus. It should also satisfy the equations -- --
--   mzero >>= f  =  mzero
--   v >> mzero   =  mzero
--   
-- -- The default definition is -- --
--   mzero = empty
--   
mzero :: MonadPlus m => m a -- | An associative operation. The default definition is -- --
--   mplus = (<|>)
--   
mplus :: MonadPlus m => m a -> m a -> m a -- | Haskell defines operations to read and write characters from and to -- files, represented by values of type Handle. Each value of -- this type is a handle: a record used by the Haskell run-time -- system to manage I/O with file system objects. A handle has at -- least the following properties: -- -- -- -- Most handles will also have a current I/O position indicating where -- the next input or output operation will occur. A handle is -- readable if it manages only input or both input and output; -- likewise, it is writable if it manages only output or both -- input and output. A handle is open when first allocated. Once -- it is closed it can no longer be used for either input or output, -- though an implementation cannot re-use its storage while references -- remain to it. Handles are in the Show and Eq classes. -- The string produced by showing a handle is system dependent; it should -- include enough information to identify the handle for debugging. A -- handle is equal according to == only to itself; no attempt is -- made to compare the internal state of different handles for equality. data () => Handle -- | A full HTTP header field with the name and value separated. -- -- E.g. "Content-Length: 28" parsed into a Header would -- turn into ("Content-Length", "28") type Header = (HeaderName, ByteString) -- | The WAI application. -- -- Note that, since WAI 3.0, this type is structured in continuation -- passing style to allow for proper safe resource handling. This was -- handled in the past via other means (e.g., ResourceT). As a -- demonstration: -- --
--   app :: Application
--   app req respond = bracket_
--       (putStrLn "Allocating scarce resource")
--       (putStrLn "Cleaning up")
--       (respond $ responseLBS status200 [] "Hello World")
--   
type Application = Request -> Response -> IO ResponseReceived -> IO ResponseReceived -- | A set of values a. data () => Set a -- | A bifunctor is a type constructor that takes two type arguments and is -- a functor in both arguments. That is, unlike with -- Functor, a type constructor such as Either does not need -- to be partially applied for a Bifunctor instance, and the -- methods in this class permit mapping functions over the Left -- value or the Right value, or both at the same time. -- -- Formally, the class Bifunctor represents a bifunctor from -- Hask -> Hask. -- -- Intuitively it is a bifunctor where both the first and second -- arguments are covariant. -- -- You can define a Bifunctor by either defining bimap or -- by defining both first and second. A partially applied -- Bifunctor must be a Functor and the second method -- must agree with fmap. From this it follows that: -- --
--   second id = id
--   
-- -- If you supply bimap, you should ensure that: -- --
--   bimap id idid
--   
-- -- If you supply first and second, ensure: -- --
--   first idid
--   second idid
--   
-- -- If you supply both, you should also ensure: -- --
--   bimap f g ≡ first f . second g
--   
-- -- These ensure by parametricity: -- --
--   bimap  (f . g) (h . i) ≡ bimap f h . bimap g i
--   first  (f . g) ≡ first  f . first  g
--   second (f . g) ≡ second f . second g
--   
-- -- Since 4.18.0.0 Functor is a superclass of 'Bifunctor. class forall a. () => Functor p a => Bifunctor (p :: Type -> Type -> Type) -- | Map over both arguments at the same time. -- --
--   bimap f g ≡ first f . second g
--   
-- --

Examples

-- --
--   >>> bimap toUpper (+1) ('j', 3)
--   ('J',4)
--   
-- --
--   >>> bimap toUpper (+1) (Left 'j')
--   Left 'J'
--   
-- --
--   >>> bimap toUpper (+1) (Right 3)
--   Right 4
--   
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d -- | Map covariantly over the first argument. -- --
--   first f ≡ bimap f id
--   
-- --

Examples

-- --
--   >>> first toUpper ('j', 3)
--   ('J',3)
--   
-- --
--   >>> first toUpper (Left 'j')
--   Left 'J'
--   
first :: Bifunctor p => (a -> b) -> p a c -> p b c -- | Map covariantly over the second argument. -- --
--   secondbimap id
--   
-- --

Examples

-- --
--   >>> second (+1) ('j', 3)
--   ('j',4)
--   
-- --
--   >>> second (+1) (Right 3)
--   Right 4
--   
second :: Bifunctor p => (b -> c) -> p a b -> p a c -- | Unlifted Concurrently. newtype () => Concurrently (m :: Type -> Type) a Concurrently :: m a -> Concurrently (m :: Type -> Type) a [runConcurrently] :: Concurrently (m :: Type -> Type) a -> m a -- | The exception thrown by cancel to terminate a thread. data () => AsyncCancelled AsyncCancelled :: AsyncCancelled -- | An asynchronous action spawned by async or withAsync. -- Asynchronous actions are executed in a separate thread, and operations -- are provided for waiting for asynchronous actions to complete and -- obtaining their results (see e.g. wait). data () => Async a -- | Functors representing data structures that can be transformed to -- structures of the same shape by performing an -- Applicative (or, therefore, Monad) action on each -- element from left to right. -- -- A more detailed description of what same shape means, the -- various methods, how traversals are constructed, and example advanced -- use-cases can be found in the Overview section of -- Data.Traversable#overview. -- -- For the class laws see the Laws section of -- Data.Traversable#laws. class (Functor t, Foldable t) => Traversable (t :: Type -> Type) -- | Map each element of a structure to an action, evaluate these actions -- from left to right, and collect the results. For a version that -- ignores the results see traverse_. -- --

Examples

-- -- Basic usage: -- -- In the first two examples we show each evaluated action mapping to the -- output structure. -- --
--   >>> traverse Just [1,2,3,4]
--   Just [1,2,3,4]
--   
-- --
--   >>> traverse id [Right 1, Right 2, Right 3, Right 4]
--   Right [1,2,3,4]
--   
-- -- In the next examples, we show that Nothing and Left -- values short circuit the created structure. -- --
--   >>> traverse (const Nothing) [1,2,3,4]
--   Nothing
--   
-- --
--   >>> traverse (\x -> if odd x then Just x else Nothing)  [1,2,3,4]
--   Nothing
--   
-- --
--   >>> traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]
--   Left 0
--   
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) -- | Evaluate each action in the structure from left to right, and collect -- the results. For a version that ignores the results see -- sequenceA_. -- --

Examples

-- -- Basic usage: -- -- For the first two examples we show sequenceA fully evaluating a a -- structure and collecting the results. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3]
--   Just [1,2,3]
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3]
--   Right [1,2,3]
--   
-- -- The next two example show Nothing and Just will short -- circuit the resulting structure if present in the input. For more -- context, check the Traversable instances for Either and -- Maybe. -- --
--   >>> sequenceA [Just 1, Just 2, Just 3, Nothing]
--   Nothing
--   
-- --
--   >>> sequenceA [Right 1, Right 2, Right 3, Left 4]
--   Left 4
--   
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. -- --

Examples

-- -- mapM is literally a traverse with a type signature -- restricted to Monad. Its implementation may be more efficient -- due to additional power of Monad. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. -- --

Examples

-- -- Basic usage: -- -- The first two examples are instances where the input and and output of -- sequence are isomorphic. -- --
--   >>> sequence $ Right [1,2,3,4]
--   [Right 1,Right 2,Right 3,Right 4]
--   
-- --
--   >>> sequence $ [Right 1,Right 2,Right 3,Right 4]
--   Right [1,2,3,4]
--   
-- -- The following examples demonstrate short circuit behavior for -- sequence. -- --
--   >>> sequence $ Left [1,2,3,4]
--   Left [1,2,3,4]
--   
-- --
--   >>> sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]
--   Left 0
--   
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | A monad supporting atomic memory transactions. data () => STM a -- | The member functions of this class facilitate writing values of -- primitive types to raw memory (which may have been allocated with the -- above mentioned routines) and reading values from blocks of raw -- memory. The class, furthermore, includes support for computing the -- storage requirements and alignment restrictions of storable types. -- -- Memory addresses are represented as values of type Ptr -- a, for some a which is an instance of class -- Storable. The type argument to Ptr helps provide some -- valuable type safety in FFI code (you can't mix pointers of different -- types without an explicit cast), while helping the Haskell type system -- figure out which marshalling method is needed for a given pointer. -- -- All marshalling between Haskell and a foreign language ultimately -- boils down to translating Haskell data structures into the binary -- representation of a corresponding data structure of the foreign -- language and vice versa. To code this marshalling in Haskell, it is -- necessary to manipulate primitive data types stored in unstructured -- memory blocks. The class Storable facilitates this manipulation -- on all types for which it is instantiated, which are the standard -- basic types of Haskell, the fixed size Int types -- (Int8, Int16, Int32, Int64), the fixed -- size Word types (Word8, Word16, Word32, -- Word64), StablePtr, all types from -- Foreign.C.Types, as well as Ptr. class () => Storable a -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data () => MVar a -- | Any type that you wish to throw or catch as an exception must be an -- instance of the Exception class. The simplest case is a new -- exception type directly below the root: -- --
--   data MyException = ThisException | ThatException
--       deriving Show
--   
--   instance Exception MyException
--   
-- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
--   *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
--   Caught ThisException
--   
-- -- In more complicated examples, you may wish to define a whole hierarchy -- of exceptions: -- --
--   ---------------------------------------------------------------------
--   -- Make the root exception type for all the exceptions in a compiler
--   
--   data SomeCompilerException = forall e . Exception e => SomeCompilerException e
--   
--   instance Show SomeCompilerException where
--       show (SomeCompilerException e) = show e
--   
--   instance Exception SomeCompilerException
--   
--   compilerExceptionToException :: Exception e => e -> SomeException
--   compilerExceptionToException = toException . SomeCompilerException
--   
--   compilerExceptionFromException :: Exception e => SomeException -> Maybe e
--   compilerExceptionFromException x = do
--       SomeCompilerException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make a subhierarchy for exceptions in the frontend of the compiler
--   
--   data SomeFrontendException = forall e . Exception e => SomeFrontendException e
--   
--   instance Show SomeFrontendException where
--       show (SomeFrontendException e) = show e
--   
--   instance Exception SomeFrontendException where
--       toException = compilerExceptionToException
--       fromException = compilerExceptionFromException
--   
--   frontendExceptionToException :: Exception e => e -> SomeException
--   frontendExceptionToException = toException . SomeFrontendException
--   
--   frontendExceptionFromException :: Exception e => SomeException -> Maybe e
--   frontendExceptionFromException x = do
--       SomeFrontendException a <- fromException x
--       cast a
--   
--   ---------------------------------------------------------------------
--   -- Make an exception type for a particular frontend compiler exception
--   
--   data MismatchedParentheses = MismatchedParentheses
--       deriving Show
--   
--   instance Exception MismatchedParentheses where
--       toException   = frontendExceptionToException
--       fromException = frontendExceptionFromException
--   
-- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
--   Caught MismatchedParentheses
--   *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
--   *** Exception: MismatchedParentheses
--   
class (Typeable e, Show e) => Exception e toException :: Exception e => e -> SomeException fromException :: Exception e => SomeException -> Maybe e -- | Render this exception value in a human-friendly manner. -- -- Default implementation: show. displayException :: Exception e => e -> String -- | a value of type STRef s a is a mutable variable in state -- thread s, containing a value of type a -- --
--   >>> :{
--   runST (do
--       ref <- newSTRef "hello"
--       x <- readSTRef ref
--       writeSTRef ref (x ++ "world")
--       readSTRef ref )
--   :}
--   "helloworld"
--   
data () => STRef s a -- | The Haskell 2010 type for exceptions in the IO monad. Any I/O -- operation may raise an IOException instead of returning a -- result. For a more general type of exception, including also those -- that arise in pure code, see Exception. -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. This allows us to run IO -- computations in any monadic stack, so long as it supports these kinds -- of operations (i.e. IO is the base monad for the stack). -- --

Example

-- --
--   import Control.Monad.Trans.State -- from the "transformers" library
--   
--   printState :: Show s => StateT s IO ()
--   printState = do
--     state <- get
--     liftIO $ print state
--   
-- -- Had we omitted liftIO, we would have ended up with -- this error: -- --
--   • Couldn't match type ‘IO’ with ‘StateT s IO’
--    Expected type: StateT s IO ()
--      Actual type: IO ()
--   
-- -- The important part here is the mismatch between StateT s IO -- () and IO (). -- -- Luckily, we know of a function that takes an IO a and -- returns an (m a): liftIO, enabling us to run -- the program and see the expected results: -- --
--   > evalStateT printState "hello"
--   "hello"
--   
--   > evalStateT printState 3
--   3
--   
liftIO :: MonadIO m => IO a -> m a -- | Chan is an abstract type representing an unbounded FIFO -- channel. data () => Chan a -- | Exceptions that occur in the IO monad. An -- IOException records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was flagged. data () => IOException -- | Trigonometric and hyperbolic functions and related functions. -- -- The Haskell Report defines no laws for Floating. However, -- (+), (*) and exp are -- customarily expected to define an exponential field and have the -- following properties: -- -- class Fractional a => Floating a pi :: Floating a => a exp :: Floating a => a -> a log :: Floating a => a -> a sqrt :: Floating a => a -> a (**) :: Floating a => a -> a -> a logBase :: Floating a => a -> a -> a sin :: Floating a => a -> a cos :: Floating a => a -> a tan :: Floating a => a -> a asin :: Floating a => a -> a acos :: Floating a => a -> a atan :: Floating a => a -> a sinh :: Floating a => a -> a cosh :: Floating a => a -> a tanh :: Floating a => a -> a asinh :: Floating a => a -> a acosh :: Floating a => a -> a atanh :: Floating a => a -> a infixr 8 ** -- | Basic numeric class. -- -- The Haskell Report defines no laws for Num. However, -- (+) and (*) are customarily expected -- to define a ring and have the following properties: -- -- -- -- Note that it isn't customarily expected that a type instance of -- both Num and Ord implement an ordered ring. Indeed, in -- base only Integer and Rational do. class () => Num a (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a -- | Unary negation. negate :: Num a => a -> a -- | Absolute value. abs :: Num a => a -> a -- | Sign of a number. The functions abs and signum should -- satisfy the law: -- --
--   abs x * signum x == x
--   
-- -- For real numbers, the signum is either -1 (negative), -- 0 (zero) or 1 (positive). signum :: Num a => a -> a -- | Conversion from an Integer. An integer literal represents the -- application of the function fromInteger to the appropriate -- value of type Integer, so such literals have type -- (Num a) => a. fromInteger :: Num a => Integer -> a infixl 6 - infixl 6 + infixl 7 * -- | Efficient, machine-independent access to the components of a -- floating-point number. class (RealFrac a, Floating a) => RealFloat a -- | a constant function, returning the radix of the representation (often -- 2) floatRadix :: RealFloat a => a -> Integer -- | a constant function, returning the number of digits of -- floatRadix in the significand floatDigits :: RealFloat a => a -> Int -- | a constant function, returning the lowest and highest values the -- exponent may assume floatRange :: RealFloat a => a -> (Int, Int) -- | The function decodeFloat applied to a real floating-point -- number returns the significand expressed as an Integer and an -- appropriately scaled exponent (an Int). If -- decodeFloat x yields (m,n), then x -- is equal in value to m*b^^n, where b is the -- floating-point radix, and furthermore, either m and -- n are both zero or else b^(d-1) <= abs m < -- b^d, where d is the value of floatDigits -- x. In particular, decodeFloat 0 = (0,0). If the -- type contains a negative zero, also decodeFloat (-0.0) = -- (0,0). The result of decodeFloat x is -- unspecified if either of isNaN x or -- isInfinite x is True. decodeFloat :: RealFloat a => a -> (Integer, Int) -- | encodeFloat performs the inverse of decodeFloat in the -- sense that for finite x with the exception of -0.0, -- uncurry encodeFloat (decodeFloat x) = x. -- encodeFloat m n is one of the two closest -- representable floating-point numbers to m*b^^n (or -- ±Infinity if overflow occurs); usually the closer, but if -- m contains too many bits, the result may be rounded in the -- wrong direction. encodeFloat :: RealFloat a => Integer -> Int -> a -- | exponent corresponds to the second component of -- decodeFloat. exponent 0 = 0 and for finite -- nonzero x, exponent x = snd (decodeFloat x) -- + floatDigits x. If x is a finite floating-point -- number, it is equal in value to significand x * b ^^ -- exponent x, where b is the floating-point radix. -- The behaviour is unspecified on infinite or NaN values. exponent :: RealFloat a => a -> Int -- | The first component of decodeFloat, scaled to lie in the open -- interval (-1,1), either 0.0 or of absolute -- value >= 1/b, where b is the floating-point -- radix. The behaviour is unspecified on infinite or NaN -- values. significand :: RealFloat a => a -> a -- | multiplies a floating-point number by an integer power of the radix scaleFloat :: RealFloat a => Int -> a -> a -- | True if the argument is an IEEE "not-a-number" (NaN) value isNaN :: RealFloat a => a -> Bool -- | True if the argument is an IEEE infinity or negative infinity isInfinite :: RealFloat a => a -> Bool -- | True if the argument is too small to be represented in -- normalized format isDenormalized :: RealFloat a => a -> Bool -- | True if the argument is an IEEE negative zero isNegativeZero :: RealFloat a => a -> Bool -- | True if the argument is an IEEE floating point number isIEEE :: RealFloat a => a -> Bool -- | a version of arctangent taking two real floating-point arguments. For -- real floating x and y, atan2 y x -- computes the angle (from the positive x-axis) of the vector from the -- origin to the point (x,y). atan2 y x returns -- a value in the range [-pi, pi]. It follows the -- Common Lisp semantics for the origin when signed zeroes are supported. -- atan2 y 1, with y in a type that is -- RealFloat, should return the same value as atan -- y. A default definition of atan2 is provided, but -- implementors can provide a more accurate implementation. atan2 :: RealFloat a => a -> a -> a -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data () => SomeException SomeException :: e -> SomeException -- | Shared memory locations that support atomic memory transactions. data () => TVar a -- | The Down type allows you to reverse sort order conveniently. A -- value of type Down a contains a value of type -- a (represented as Down a). -- -- If a has an Ord instance associated with it -- then comparing two values thus wrapped will give you the opposite of -- their normal sort order. This is particularly useful when sorting in -- generalised list comprehensions, as in: then sortWith by -- Down x. -- --
--   >>> compare True False
--   GT
--   
-- --
--   >>> compare (Down True) (Down False)
--   LT
--   
-- -- If a has a Bounded instance then the wrapped -- instance also respects the reversed ordering by exchanging the values -- of minBound and maxBound. -- --
--   >>> minBound :: Int
--   -9223372036854775808
--   
-- --
--   >>> minBound :: Down Int
--   Down 9223372036854775807
--   
-- -- All other instances of Down a behave as they do for -- a. newtype () => Down a Down :: a -> Down a [getDown] :: Down a -> a -- | See openFile data () => IOMode ReadMode :: IOMode WriteMode :: IOMode AppendMode :: IOMode ReadWriteMode :: IOMode -- | File and directory names are values of type String, whose -- precise meaning is operating system dependent. Files can be opened, -- yielding a handle which can then be used to operate on the contents of -- that file. type FilePath = String -- | A mutable variable in the IO monad. -- --
--   >>> import Data.IORef
--   
--   >>> r <- newIORef 0
--   
--   >>> readIORef r
--   0
--   
--   >>> writeIORef r 1
--   
--   >>> readIORef r
--   1
--   
--   >>> atomicWriteIORef r 2
--   
--   >>> readIORef r
--   2
--   
--   >>> modifyIORef' r (+ 1)
--   
--   >>> readIORef r
--   3
--   
--   >>> atomicModifyIORef' r (\a -> (a + 1, ()))
--   
--   >>> readIORef r
--   4
--   
-- -- See also STRef and MVar. data () => IORef a -- | A mode that determines the effect of hSeek hdl mode i. data () => SeekMode -- | the position of hdl is set to i. AbsoluteSeek :: SeekMode -- | the position of hdl is set to offset i from the -- current position. RelativeSeek :: SeekMode -- | the position of hdl is set to offset i from the end -- of the file. SeekFromEnd :: SeekMode -- | Three kinds of buffering are supported: line-buffering, -- block-buffering or no-buffering. These modes have the following -- effects. For output, items are written out, or flushed, from -- the internal buffer according to the buffer mode: -- -- -- -- An implementation is free to flush the buffer more frequently, but not -- less frequently, than specified above. The output buffer is emptied as -- soon as it has been written out. -- -- Similarly, input occurs according to the buffer mode for the handle: -- -- -- -- The default buffering mode when a handle is opened is -- implementation-dependent and may depend on the file system object -- which is attached to that handle. For most implementations, physical -- files will normally be block-buffered and terminals will normally be -- line-buffered. data () => BufferMode -- | buffering is disabled if possible. NoBuffering :: BufferMode -- | line-buffering should be enabled if possible. LineBuffering :: BufferMode -- | block-buffering should be enabled if possible. The size of the buffer -- is n items if the argument is Just n and is -- otherwise implementation-dependent. BlockBuffering :: Maybe Int -> BufferMode -- | An abstract type that contains a value for each variant of -- IOException. data () => IOErrorType -- | Superclass for asynchronous exceptions. data () => SomeAsyncException SomeAsyncException :: e -> SomeAsyncException type Limit = Int64 -- | Identity functor and monad. (a non-strict monad) newtype () => Identity a Identity :: a -> Identity a [runIdentity] :: Identity a -> a data () => Option a Option :: Text -> a -> Text -> Option a -- | The user-facing label. [optionDisplay] :: Option a -> Text -- | The Haskell value being selected. [optionInternalValue] :: Option a -> a -- | The representation of this value stored in the form. [optionExternalValue] :: Option a -> Text -- | Unique keys besides the Key. data family Unique record -- | QSemN is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSemN calls. -- -- The pattern -- --
--   bracket_ (waitQSemN n) (signalQSemN n) (...)
--   
-- -- is safe; it never loses any of the resource. data () => QSemN -- | QSem is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSem calls. -- -- The pattern -- --
--   bracket_ waitQSem signalQSem (...)
--   
-- -- is safe; it never loses a unit of the resource. data () => QSem -- | Provide a Semigroup for an arbitrary Monoid. -- -- NOTE: This is not needed anymore since Semigroup became -- a superclass of Monoid in base-4.11 and this newtype be -- deprecated at some point in the future. data () => WrappedMonoid m -- | Class of monads which can perform primitive state-transformer actions. class Monad m => PrimMonad (m :: Type -> Type) where { -- | State token type. type family PrimState (m :: Type -> Type); } -- | Execute a primitive operation. primitive :: PrimMonad m => (State# (PrimState m) -> (# State# (PrimState m), a #)) -> m a -- | State token type. type family PrimState (m :: Type -> Type) -- | General-purpose finite sequences. data () => Seq a -- | A set of integers. data () => IntSet -- | A map of integers to values a. data () => IntMap a -- | A set of values. A set cannot contain duplicate values. data () => HashSet a class (Vector Vector a, MVector MVector a) => Unbox a type SVector = Vector type UVector = Vector type LByteString = ByteString type LText = Text type Html = Markup type Tag = Text data () => Content -- | The content and optional content length. ContentBuilder :: !Builder -> !Maybe Int -> Content ContentSource :: !ConduitT () (Flush Builder) (ResourceT IO) () -> Content ContentFile :: !FilePath -> !Maybe FilePart -> Content ContentDontEvaluate :: !Content -> Content -- | Type used for the subsite with static contents. newtype () => Static Static :: StaticSettings -> Static -- | A double-ended queue supporting any underlying vector type and any -- monad. -- -- This implements a circular double-ended queue with exponential growth. -- -- Since 0.2.0 data () => Deque (v :: Type -> Type -> Type) s a -- | Since 0.1.0.0 class () => ToBuilder value builder -- | Since 0.1.0.0 toBuilder :: ToBuilder value builder => value -> builder -- | Since 0.3.0.0 type ByteStringBuilder = Builder -- | Since 0.1.0.0 type BlazeBuilder = Builder -- | Since 0.1.0.0 type TextBuilder = Builder -- | A more efficient alternative to Concurrently, which reduces the -- number of threads that need to be forked. For more information, see -- this blog post. This is provided as a separate type to -- Concurrently as it has a slightly different API. -- -- Use the conc function to construct values of type Conc, -- and runConc to execute the composed actions. You can use the -- Applicative instance to run different actions and wait for -- all of them to complete, or the Alternative instance to wait -- for the first thread to complete. -- -- In the event of a runtime exception thrown by any of the children -- threads, or an asynchronous exception received in the parent thread, -- all threads will be killed with an AsyncCancelled exception and -- the original exception rethrown. If multiple exceptions are generated -- by different threads, there are no guarantees on which exception will -- end up getting rethrown. -- -- For many common use cases, you may prefer using helper functions in -- this module like mapConcurrently. -- -- There are some intentional differences in behavior to -- Concurrently: -- -- -- -- Note that it is a programmer error to use the Alternative -- instance in such a way that there are no alternatives to an empty, -- e.g. runConc (empty | empty). In such a case, a -- ConcException will be thrown. If there was an -- Alternative in the standard libraries without empty, -- this library would use it instead. data () => Conc (m :: Type -> Type) a -- | A class of types that can be fully evaluated. class () => NFData a -- | rnf should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return (). -- --

Generic NFData deriving

-- -- Starting with GHC 7.2, you can automatically derive instances for -- types possessing a Generic instance. -- -- Note: Generic1 can be auto-derived starting with GHC 7.4 -- --
--   {-# LANGUAGE DeriveGeneric #-}
--   
--   import GHC.Generics (Generic, Generic1)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1)
--   
--   instance NFData a => NFData (Foo a)
--   instance NFData1 Foo
--   
--   data Colour = Red | Green | Blue
--                 deriving Generic
--   
--   instance NFData Colour
--   
-- -- Starting with GHC 7.10, the example above can be written more -- concisely by enabling the new DeriveAnyClass extension: -- --
--   {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
--   
--   import GHC.Generics (Generic)
--   import Control.DeepSeq
--   
--   data Foo a = Foo a String
--                deriving (Eq, Generic, Generic1, NFData, NFData1)
--   
--   data Colour = Red | Green | Blue
--                 deriving (Generic, NFData)
--   
-- --

Compatibility with previous deepseq versions

-- -- Prior to version 1.4.0.0, the default implementation of the rnf -- method was defined as -- --
--   rnf a = seq a ()
--   
-- -- However, starting with deepseq-1.4.0.0, the default -- implementation is based on DefaultSignatures allowing for -- more accurate auto-derived NFData instances. If you need the -- previously used exact default rnf method implementation -- semantics, use -- --
--   instance NFData Colour where rnf x = seq x ()
--   
-- -- or alternatively -- --
--   instance NFData Colour where rnf = rwhnf
--   
-- -- or -- --
--   {-# LANGUAGE BangPatterns #-}
--   instance NFData Colour where rnf !_ = ()
--   
rnf :: NFData a => a -> () -- | A difference list is an abstraction representing a list that supports -- <math>(1) append and snoc operations, -- making it useful for replacing frequent applications of ++ such -- as logging and pretty printing (esp. if those uses of ++ are -- left-nested). data () => DList a -- | The Modified Julian Day is a standard count of days, with zero being -- the day 1858-11-17. newtype () => Day ModifiedJulianDay :: Integer -> Day [toModifiedJulianDay] :: Day -> Integer -- | Wrap up a synchronous exception to be treated as an asynchronous -- exception -- -- This is intended to be created via toAsyncException data () => AsyncExceptionWrapper AsyncExceptionWrapper :: e -> AsyncExceptionWrapper -- | Wrap up an asynchronous exception to be treated as a synchronous -- exception -- -- This is intended to be created via toSyncException data () => SyncExceptionWrapper SyncExceptionWrapper :: e -> SyncExceptionWrapper -- | Exception type thrown by throwString. -- -- Note that the second field of the data constructor depends on GHC/base -- version. For base 4.9 and GHC 8.0 and later, the second field is a -- call stack. Previous versions of GHC and base do not support call -- stacks, and the field is simply unit (provided to make pattern -- matching across GHC versions easier). data () => StringException StringException :: String -> CallStack -> StringException -- | TBQueue is an abstract type representing a bounded FIFO -- channel. data () => TBQueue a -- | TChan is an abstract type representing an unbounded FIFO -- channel. data () => TChan a -- | A TMVar is a synchronising variable, used for communication -- between concurrent threads. It can be thought of as a box, which may -- be empty or full. data () => TMVar a -- | TQueue is an abstract type representing an unbounded FIFO -- channel. data () => TQueue a -- | Things that can go wrong in the structure of a Conc. These are -- programmer errors. data () => ConcException EmptyWithNoAlternative :: ConcException -- | A "run once" value, with results saved. Extract the value with -- runMemoized. For single-threaded usage, you can use -- memoizeRef to create a value. If you need guarantees that only -- one thread will run the action at a time, use memoizeMVar. -- -- Note that this type provides a Show instance for convenience, -- but not useful information can be provided. data () => Memoized a -- | Monads which allow their actions to be run in IO. -- -- While MonadIO allows an IO action to be lifted into -- another monad, this class captures the opposite concept: allowing you -- to capture the monadic context. Note that, in order to meet the laws -- given below, the intuition is that a monad must have no monadic state, -- but may have monadic context. This essentially limits -- MonadUnliftIO to ReaderT and IdentityT -- transformers on top of IO. -- -- Laws. For any function run provided by withRunInIO, it -- must meet the monad transformer laws as reformulated for -- MonadUnliftIO: -- -- -- -- Instances of MonadUnliftIO must also satisfy the following -- laws: -- -- -- -- As an example of an invalid instance, a naive implementation of -- MonadUnliftIO (StateT s m) might be -- --
--   withRunInIO inner =
--     StateT $ \s ->
--       withRunInIO $ \run ->
--         inner (run . flip evalStateT s)
--   
-- -- This breaks the identity law because the inner run m would -- throw away any state changes in m. class MonadIO m => MonadUnliftIO (m :: Type -> Type) -- | Convenience function for capturing the monadic context and running an -- IO action with a runner function. The runner function is used -- to run a monadic action m in IO. withRunInIO :: MonadUnliftIO m => ((forall a. () => m a -> IO a) -> IO b) -> m b -- | A MutVar behaves like a single-element mutable array associated -- with a primitive state token. data () => MutVar s a MutVar :: MutVar# s a -> MutVar s a -- | Class of types supporting primitive array operations. This includes -- interfacing with GC-managed memory (functions suffixed with -- ByteArray#) and interfacing with unmanaged memory (functions -- suffixed with Addr#). Endianness is platform-dependent. class () => Prim a -- | Collections which allow pushing and popping at the front and back. -- -- Since 0.2.0 type MutableDeque c = (MutableQueue c, MutablePushFront c, MutablePopBack c) -- | Collections which allow pushing at the back and popping at the front -- (aka FILOs). -- -- Since 0.2.0 type MutableStack c = (MutablePopFront c, MutablePushFront c) -- | Collections which allow pushing and popping at the front (aka FIFOs). -- -- Since 0.2.0 type MutableQueue c = (MutablePopFront c, MutablePushBack c) -- | Place a value at the back of the collection. -- -- Since 0.2.0 class MutableCollection c => MutablePushBack c -- | Place a value at the back of the collection. -- -- Since 0.2.0 pushBack :: (MutablePushBack c, PrimMonad m, PrimState m ~ MCState c) => c -> CollElement c -> m () -- | Take a value from the back of the collection, if available. -- -- Since 0.2.0 class MutableCollection c => MutablePopBack c -- | Take a value from the back of the collection, if available. -- -- Since 0.2.0 popBack :: (MutablePopBack c, PrimMonad m, PrimState m ~ MCState c) => c -> m (Maybe (CollElement c)) -- | Place a value at the front of the collection. -- -- Since 0.2.0 class MutableCollection c => MutablePushFront c -- | Place a value at the front of the collection. -- -- Since 0.2.0 pushFront :: (MutablePushFront c, PrimMonad m, PrimState m ~ MCState c) => c -> CollElement c -> m () -- | Take a value from the front of the collection, if available. -- -- Since 0.2.0 class MutableCollection c => MutablePopFront c -- | Take a value from the front of the collection, if available. -- -- Since 0.2.0 popFront :: (MutablePopFront c, PrimMonad m, PrimState m ~ MCState c) => c -> m (Maybe (CollElement c)) -- | Containers which contain 0 or more values. -- -- Since 0.2.0 class MutableContainer c => MutableCollection c where { -- | The type of each value in the collection. -- -- Since 0.2.0 type family CollElement c; } -- | Create a new, empty collection. -- -- Since 0.2.0 newColl :: (MutableCollection c, PrimMonad m, PrimState m ~ MCState c) => m c -- | The type of each value in the collection. -- -- Since 0.2.0 type family CollElement c -- | MutableRefs that provide for atomic modifications of their -- contents. -- -- Since 0.2.0 class MutableRef c => MutableAtomicRef c -- | Modify the value without necessarily forcing the result. -- -- Since 0.2.0 atomicModifyRef :: (MutableAtomicRef c, PrimMonad m, PrimState m ~ MCState c) => c -> (RefElement c -> (RefElement c, a)) -> m a -- | Modify the value, forcing the result. -- -- Since 0.2.0 atomicModifyRef' :: (MutableAtomicRef c, PrimMonad m, PrimState m ~ MCState c) => c -> (RefElement c -> (RefElement c, a)) -> m a -- | Typeclass for single-cell mutable references. -- -- Since 0.2.0 class MutableContainer c => MutableRef c where { -- | Associated type giving the type of the value inside the mutable -- reference. -- -- Since 0.2.0 type family RefElement c; } -- | Create a new mutable reference with the given value. -- -- Since 0.2.0 newRef :: (MutableRef c, PrimMonad m, PrimState m ~ MCState c) => RefElement c -> m c -- | Read the current value in the mutable reference. -- -- Since 0.2.0 readRef :: (MutableRef c, PrimMonad m, PrimState m ~ MCState c) => c -> m (RefElement c) -- | Write a new value to the mutable reference. -- -- Since 0.2.0 writeRef :: (MutableRef c, PrimMonad m, PrimState m ~ MCState c) => c -> RefElement c -> m () -- | Modify the value in the mutable reference, without necessarily forcing -- the result. -- -- Note: some implementations will force the result, in particular -- PRef, SRef, and URef. -- -- Since 0.2.0 modifyRef :: (MutableRef c, PrimMonad m, PrimState m ~ MCState c) => c -> (RefElement c -> RefElement c) -> m () -- | Modify the value in the mutable reference, forcing the result. -- -- Since 0.2.0 modifyRef' :: (MutableRef c, PrimMonad m, PrimState m ~ MCState c) => c -> (RefElement c -> RefElement c) -> m () -- | Associated type giving the type of the value inside the mutable -- reference. -- -- Since 0.2.0 type family RefElement c -- | The parent typeclass for all mutable containers. -- -- Since 0.2.0 class () => MutableContainer c where { -- | Associated type giving the primitive state token for the given -- container, much like PrimState from primitive. -- -- Since 0.2.0 type family MCState c; } -- | Associated type giving the primitive state token for the given -- container, much like PrimState from primitive. -- -- Since 0.2.0 type family MCState c -- | A boxed IO vector reference. type IOBRef = BRef PrimState IO -- | A boxed vector reference, supporting any monad. -- -- Since 0.2.0 data () => BRef s a -- | A doubly-linked list. -- -- Since 0.3.0 data () => DLList s a -- | A Deque specialized to boxed vectors. -- -- Since 0.2.0 type BDeque = Deque MVector -- | A Deque specialized to storable vectors. -- -- Since 0.2.0 type SDeque = Deque MVector -- | A Deque specialized to unboxed vectors. -- -- Since 0.2.0 type UDeque = Deque MVector -- | A primitive ByteArray IO reference. type IOPRef = PRef PrimState IO -- | A primitive ByteArray reference, supporting any monad. -- -- Since 0.2.0 data () => PRef s a -- | A storable IO vector reference. type IOSRef = SRef PrimState IO -- | A storable vector reference, supporting any monad. -- -- Since 0.2.0 data () => SRef s a -- | An unboxed IO vector reference. type IOURef = URef PrimState IO -- | An unboxed vector reference, supporting any monad. -- -- Since 0.2.0 data () => URef s a -- | TBChan is an abstract type representing a bounded FIFO -- channel. data () => TBChan a -- | TBMChan is an abstract type representing a bounded closeable -- FIFO channel. data () => TBMChan a -- | TBMQueue is an abstract type representing a bounded closeable -- FIFO queue. data () => TBMQueue a -- | TMChan is an abstract type representing a closeable FIFO -- channel. data () => TMChan a -- | TMQueue is an abstract type representing a closeable FIFO -- queue. data () => TMQueue a -- | Provides a Foldable for an arbitrary MonoFoldable. data () => WrappedMono mono a [WrappedMono] :: forall mono a. Element mono ~ a => mono -> WrappedMono mono a -- | Provides a MonoFoldable, MonoFunctor or -- MonoPointed for an arbitrary Foldable, Functor or -- Applicative. -- -- Useful for, e.g., passing a Foldable type you don't own into a -- function that expects a MonoFoldable. -- --
--   // package A
--   data MyList a = MyList [a] deriving Foldable
--   
--   // package B
--   process :: MonoFoldable mono => mono -> IO ()
--   
--   // package C
--   process (WrappedPoly (MyList []))
--   
newtype () => WrappedPoly (f :: Type -> Type) a WrappedPoly :: f a -> WrappedPoly (f :: Type -> Type) a [unwrapPoly] :: WrappedPoly (f :: Type -> Type) a -> f a -- | Containers which, when two values are combined, the combined length is -- no less than the larger of the two inputs. In code: -- --
--   olength (x <> y) >= max (olength x) (olength y)
--   
-- -- This class has no methods, and is simply used to assert that this law -- holds, in order to provide guarantees of correctness (see, for -- instance, Data.NonNull). -- -- This should have a Semigroup superclass constraint, however, -- due to Semigroup only recently moving to base, some packages -- do not provide instances. class MonoFoldable mono => GrowingAppend mono -- | Typeclass for monomorphic containers where it is always okay to -- "extract" a value from with oextract, and where you can -- extrapolate any "extracting" function to be a function on the whole -- part with oextend. -- -- oextend and oextract should work together following the -- laws: -- --
--   oextend oextract      = id
--   oextract . oextend f  = f
--   oextend f . oextend g = oextend (f . oextend g)
--   
-- -- As an intuition, oextend f uses f to "build -- up" a new mono with pieces from the old one received by -- f. class MonoFunctor mono => MonoComonad mono -- | Extract an element from mono. Can be thought of as a dual -- concept to opoint. oextract :: MonoComonad mono => mono -> Element mono -- | Extend a mono -> Element mono function to be -- a mono -> mono; that is, builds a new mono from -- the old one by using pieces glimpsed from the given function. oextend :: MonoComonad mono => (mono -> Element mono) -> mono -> mono -- | Typeclass for monomorphic containers that an element can be lifted -- into. -- -- For any MonoFunctor, the following law holds: -- --
--   omap f . opoint = opoint . f
--   
class () => MonoPointed mono -- | Lift an element into a monomorphic container. -- -- opoint is the same as pure for an Applicative opoint :: MonoPointed mono => Element mono -> mono -- | Monomorphic containers that can be traversed from left to right. -- -- NOTE: Due to limitations with the role system, GHC is yet unable to -- provide newtype-derivation of MonoTraversable. See -- https://stackoverflow.com/questions/49776924/newtype-deriving-issequence. class (MonoFunctor mono, MonoFoldable mono) => MonoTraversable mono -- | Map each element of a monomorphic container to an action, evaluate -- these actions from left to right, and collect the results. otraverse :: (MonoTraversable mono, Applicative f) => (Element mono -> f (Element mono)) -> mono -> f mono -- | Map each element of a monomorphic container to a monadic action, -- evaluate these actions from left to right, and collect the results. omapM :: (MonoTraversable mono, Applicative m) => (Element mono -> m (Element mono)) -> mono -> m mono -- | Monomorphic containers that can be folded. class () => MonoFoldable mono -- | Map each element of a monomorphic container to a Monoid and -- combine the results. ofoldMap :: (MonoFoldable mono, Monoid m) => (Element mono -> m) -> mono -> m -- | Right-associative fold of a monomorphic container. ofoldr :: MonoFoldable mono => (Element mono -> b -> b) -> b -> mono -> b -- | Strict left-associative fold of a monomorphic container. ofoldl' :: MonoFoldable mono => (a -> Element mono -> a) -> a -> mono -> a -- | Convert a monomorphic container to a list. otoList :: MonoFoldable mono => mono -> [Element mono] -- | Are all of the elements in a monomorphic container converted to -- booleans True? oall :: MonoFoldable mono => (Element mono -> Bool) -> mono -> Bool -- | Are any of the elements in a monomorphic container converted to -- booleans True? oany :: MonoFoldable mono => (Element mono -> Bool) -> mono -> Bool -- | Is the monomorphic container empty? onull :: MonoFoldable mono => mono -> Bool -- | Length of a monomorphic container, returns a Int. olength :: MonoFoldable mono => mono -> Int -- | Length of a monomorphic container, returns a Int64. olength64 :: MonoFoldable mono => mono -> Int64 -- | Compare the length of a monomorphic container and a given number. ocompareLength :: (MonoFoldable mono, Integral i) => mono -> i -> Ordering -- | Map each element of a monomorphic container to an action, evaluate -- these actions from left to right, and ignore the results. otraverse_ :: (MonoFoldable mono, Applicative f) => (Element mono -> f b) -> mono -> f () -- | ofor_ is otraverse_ with its arguments flipped. ofor_ :: (MonoFoldable mono, Applicative f) => mono -> (Element mono -> f b) -> f () -- | Map each element of a monomorphic container to a monadic action, -- evaluate these actions from left to right, and ignore the results. omapM_ :: (MonoFoldable mono, Applicative m) => (Element mono -> m ()) -> mono -> m () -- | oforM_ is omapM_ with its arguments flipped. oforM_ :: (MonoFoldable mono, Applicative m) => mono -> (Element mono -> m ()) -> m () -- | Monadic fold over the elements of a monomorphic container, associating -- to the left. ofoldlM :: (MonoFoldable mono, Monad m) => (a -> Element mono -> m a) -> a -> mono -> m a -- | Map each element of a monomorphic container to a semigroup, and -- combine the results. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See ofoldMap1 from Data.NonNull for a total version -- of this function. ofoldMap1Ex :: (MonoFoldable mono, Semigroup m) => (Element mono -> m) -> mono -> m -- | Right-associative fold of a monomorphic container with no base -- element. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See ofoldr1 from Data.NonNull for a total version of -- this function. ofoldr1Ex :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> mono -> Element mono -- | Strict left-associative fold of a monomorphic container with no base -- element. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See ofoldl1' from Data.NonNull for a total version of -- this function. ofoldl1Ex' :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> mono -> Element mono -- | Get the first element of a monomorphic container. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See head from Data.NonNull for a total version of -- this function. headEx :: MonoFoldable mono => mono -> Element mono -- | Get the last element of a monomorphic container. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See last from Data.NonNull for a total version of -- this function. lastEx :: MonoFoldable mono => mono -> Element mono -- | Equivalent to headEx. unsafeHead :: MonoFoldable mono => mono -> Element mono -- | Equivalent to lastEx. unsafeLast :: MonoFoldable mono => mono -> Element mono -- | Get the maximum element of a monomorphic container, using a supplied -- element ordering function. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See maximiumBy from Data.NonNull for a total version -- of this function. maximumByEx :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> mono -> Element mono -- | Get the minimum element of a monomorphic container, using a supplied -- element ordering function. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See minimumBy from Data.NonNull for a total version -- of this function. minimumByEx :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> mono -> Element mono -- | Checks if the monomorphic container includes the supplied element. oelem :: MonoFoldable mono => Element mono -> mono -> Bool -- | Checks if the monomorphic container does not include the supplied -- element. onotElem :: MonoFoldable mono => Element mono -> mono -> Bool -- | Monomorphic containers that can be mapped over. class () => MonoFunctor mono -- | Map over a monomorphic container omap :: MonoFunctor mono => (Element mono -> Element mono) -> mono -> mono -- | Type family for getting the type of the elements of a monomorphic -- container. type family Element mono -- | Textual data which can be encoded to and decoded from UTF8. class (Textual textual, IsSequence binary) => Utf8 textual binary | textual -> binary, binary -> textual -- | Encode from textual to binary using UTF-8 encoding encodeUtf8 :: Utf8 textual binary => textual -> binary -- | Note that this function is required to be pure. In the case of a -- decoding error, Unicode replacement characters must be used. decodeUtf8 :: Utf8 textual binary => binary -> textual -- | Lazy sequences containing strict chunks of data. class (IsSequence lazy, IsSequence strict) => LazySequence lazy strict | lazy -> strict, strict -> lazy toChunks :: LazySequence lazy strict => lazy -> [strict] fromChunks :: LazySequence lazy strict => [strict] -> lazy toStrict :: LazySequence lazy strict => lazy -> strict fromStrict :: LazySequence lazy strict => strict -> lazy -- | A typeclass for sequences whose elements are Chars. class (IsSequence t, IsString t, Element t ~ Char) => Textual t -- | Break up a textual sequence into a list of words, which were delimited -- by white space. -- --
--   > words "abc  def ghi"
--   ["abc","def","ghi"]
--   
words :: Textual t => t -> [t] -- | Join a list of textual sequences using seperating spaces. -- --
--   > unwords ["abc","def","ghi"]
--   "abc def ghi"
--   
unwords :: (Textual t, Element seq ~ t, MonoFoldable seq) => seq -> t -- | Break up a textual sequence at newline characters. -- --
--   > lines "hello\nworld"
--   ["hello","world"]
--   
lines :: Textual t => t -> [t] -- | Join a list of textual sequences using newlines. -- --
--   > unlines ["abc","def","ghi"]
--   "abc\ndef\nghi"
--   
unlines :: (Textual t, Element seq ~ t, MonoFoldable seq) => seq -> t -- | Convert a textual sequence to lower-case. -- --
--   > toLower "HELLO WORLD"
--   "hello world"
--   
toLower :: Textual t => t -> t -- | Convert a textual sequence to upper-case. -- --
--   > toUpper "hello world"
--   "HELLO WORLD"
--   
toUpper :: Textual t => t -> t -- | Convert a textual sequence to folded-case. -- -- Slightly different from toLower, see -- Data.Text.toCaseFold toCaseFold :: Textual t => t -> t -- | Split a textual sequence into two parts, split at the first space. -- --
--   > breakWord "hello world"
--   ("hello","world")
--   
breakWord :: Textual t => t -> (t, t) -- | Split a textual sequence into two parts, split at the newline. -- --
--   > breakLine "abc\ndef"
--   ("abc","def")
--   
breakLine :: Textual t => t -> (t, t) -- | Sequence Laws: -- --
--   fromList . otoList = id
--   fromList (x <> y) = fromList x <> fromList y
--   otoList (fromList x <> fromList y) = x <> y
--   
class (Monoid seq, MonoTraversable seq, SemiSequence seq, MonoPointed seq) => IsSequence seq -- | Convert a list to a sequence. -- --
--   > fromList [a, b, c] :: Text
--   "abc"
--   
fromList :: IsSequence seq => [Element seq] -> seq -- | lengthIndex returns the length of a sequence as -- Index seq. lengthIndex :: IsSequence seq => seq -> Index seq -- | break applies a predicate to a sequence, and returns a tuple -- where the first element is the longest prefix (possibly empty) of -- elements that do not satisfy the predicate. The second element -- of the tuple is the remainder of the sequence. -- -- break p is equivalent to span (not -- . p) -- --
--   > break (> 3) (fromList [1,2,3,4,1,2,3,4] :: Vector Int)
--   (fromList [1,2,3],fromList [4,1,2,3,4])
--   
--   > break (< z) (fromList "abc" :: Text)
--   ("","abc")
--   
--   > break (> z) (fromList "abc" :: Text)
--   ("abc","")
--   
break :: IsSequence seq => (Element seq -> Bool) -> seq -> (seq, seq) -- | span applies a predicate to a sequence, and returns a tuple -- where the first element is the longest prefix (possibly empty) that -- does satisfy the predicate. The second element of the tuple is -- the remainder of the sequence. -- -- span p xs is equivalent to (takeWhile p xs, -- dropWhile p xs) -- --
--   > span (< 3) (fromList [1,2,3,4,1,2,3,4] :: Vector Int)
--   (fromList [1,2],fromList [3,4,1,2,3,4])
--   
--   > span (< z) (fromList "abc" :: Text)
--   ("abc","")
--   
--   > span (< 0) 1,2,3
--   
span :: IsSequence seq => (Element seq -> Bool) -> seq -> (seq, seq) -- | dropWhile returns the suffix remaining after takeWhile. -- --
--   > dropWhile (< 3) [1,2,3,4,5,1,2,3]
--   [3,4,5,1,2,3]
--   
--   > dropWhile (< z) (fromList "abc" :: Text)
--   ""
--   
dropWhile :: IsSequence seq => (Element seq -> Bool) -> seq -> seq -- | takeWhile applies a predicate to a sequence, and returns the -- longest prefix (possibly empty) of the sequence of elements that -- satisfy the predicate. -- --
--   > takeWhile (< 3) [1,2,3,4,5,1,2,3]
--   [1,2]
--   
--   > takeWhile (< z) (fromList "abc" :: Text)
--   "abc"
--   
takeWhile :: IsSequence seq => (Element seq -> Bool) -> seq -> seq -- | splitAt n se returns a tuple where the first element -- is the prefix of the sequence se with length n, and -- the second element is the remainder of the sequence. -- --
--   > splitAt 6 "Hello world!"
--   ("Hello ","world!")
--   
--   > splitAt 3 (fromList [1,2,3,4,5] :: Vector Int)
--   (fromList [1,2,3],fromList [4,5])
--   
splitAt :: IsSequence seq => Index seq -> seq -> (seq, seq) -- | Equivalent to splitAt. unsafeSplitAt :: IsSequence seq => Index seq -> seq -> (seq, seq) -- | take n returns the prefix of a sequence of length -- n, or the sequence itself if n > olength -- seq. -- --
--   > take 3 "abcdefg"
--   "abc"
--   > take 4 (fromList [1,2,3,4,5,6] :: Vector Int)
--   fromList [1,2,3,4]
--   
take :: IsSequence seq => Index seq -> seq -> seq -- | Equivalent to take. unsafeTake :: IsSequence seq => Index seq -> seq -> seq -- | drop n returns the suffix of a sequence after the -- first n elements, or an empty sequence if n > -- olength seq. -- --
--   > drop 3 "abcdefg"
--   "defg"
--   > drop 4 (fromList [1,2,3,4,5,6] :: Vector Int)
--   fromList [5,6]
--   
drop :: IsSequence seq => Index seq -> seq -> seq -- | Equivalent to drop unsafeDrop :: IsSequence seq => Index seq -> seq -> seq -- | Same as drop but drops from the end of the sequence instead. -- --
--   > dropEnd 3 "abcdefg"
--   "abcd"
--   > dropEnd 4 (fromList [1,2,3,4,5,6] :: Vector Int)
--   fromList [1,2]
--   
dropEnd :: IsSequence seq => Index seq -> seq -> seq -- | partition takes a predicate and a sequence and returns the pair -- of sequences of elements which do and do not satisfy the predicate. -- --
--   partition p se = (filter p se, filter (not . p) se)
--   
partition :: IsSequence seq => (Element seq -> Bool) -> seq -> (seq, seq) -- | uncons returns the tuple of the first element of a sequence and -- the rest of the sequence, or Nothing if the sequence is empty. -- --
--   > uncons (fromList [1,2,3,4] :: Vector Int)
--   Just (1,fromList [2,3,4])
--   
--   > uncons ([] :: [Int])
--   Nothing
--   
uncons :: IsSequence seq => seq -> Maybe (Element seq, seq) -- | unsnoc returns the tuple of the init of a sequence and the last -- element, or Nothing if the sequence is empty. -- --
--   > unsnoc (fromList [1,2,3,4] :: Vector Int)
--   Just (fromList [1,2,3],4)
--   
--   > unsnoc ([] :: [Int])
--   Nothing
--   
unsnoc :: IsSequence seq => seq -> Maybe (seq, Element seq) -- | filter given a predicate returns a sequence of all elements -- that satisfy the predicate. -- --
--   > filter (< 5) [1 .. 10]
--   [1,2,3,4]
--   
filter :: IsSequence seq => (Element seq -> Bool) -> seq -> seq -- | The monadic version of filter. filterM :: (IsSequence seq, Monad m) => (Element seq -> m Bool) -> seq -> m seq -- | replicate n x is a sequence of length n with -- x as the value of every element. -- --
--   > replicate 10 a :: Text
--   "aaaaaaaaaa"
--   
replicate :: IsSequence seq => Index seq -> Element seq -> seq -- | The monadic version of replicateM. replicateM :: (IsSequence seq, Monad m) => Index seq -> m (Element seq) -> m seq -- | group takes a sequence and returns a list of sequences such -- that the concatenation of the result is equal to the argument. Each -- subsequence in the result contains only equal elements, using the -- supplied equality test. -- --
--   > groupBy (==) Mississippi
--   [M,"i","ss","i","ss","i","pp","i"]
--   
groupBy :: IsSequence seq => (Element seq -> Element seq -> Bool) -> seq -> [seq] -- | Similar to standard groupBy, but operates on the whole -- collection, not just the consecutive items. groupAllOn :: (IsSequence seq, Eq b) => (Element seq -> b) -> seq -> [seq] -- | subsequences returns a list of all subsequences of the -- argument. -- --
--   > subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   
subsequences :: IsSequence seq => seq -> [seq] -- | permutations returns a list of all permutations of the -- argument. -- --
--   > permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   
permutations :: IsSequence seq => seq -> [seq] -- | Unsafe -- -- Get the tail of a sequence, throw an exception if the sequence is -- empty. -- --
--   > tailEx [1,2,3]
--   [2,3]
--   
tailEx :: IsSequence seq => seq -> seq -- | Safe version of tailEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. tailMay :: IsSequence seq => seq -> Maybe seq -- | Unsafe -- -- Get the init of a sequence, throw an exception if the sequence is -- empty. -- --
--   > initEx [1,2,3]
--   [1,2]
--   
initEx :: IsSequence seq => seq -> seq -- | Safe version of initEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. initMay :: IsSequence seq => seq -> Maybe seq -- | Equivalent to tailEx. unsafeTail :: IsSequence seq => seq -> seq -- | Equivalent to initEx. unsafeInit :: IsSequence seq => seq -> seq -- | Get the element of a sequence at a certain index, returns -- Nothing if that index does not exist. -- --
--   > index (fromList [1,2,3] :: Vector Int) 1
--   Just 2
--   > index (fromList [1,2,3] :: Vector Int) 4
--   Nothing
--   
index :: IsSequence seq => seq -> Index seq -> Maybe (Element seq) -- | Unsafe -- -- Get the element of a sequence at a certain index, throws an exception -- if the index does not exist. indexEx :: IsSequence seq => seq -> Index seq -> Element seq -- | Equivalent to indexEx. unsafeIndex :: IsSequence seq => seq -> Index seq -> Element seq -- | splitWhen splits a sequence into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. The number of -- resulting components is greater by one than number of separators. -- -- Since 0.9.3 splitWhen :: IsSequence seq => (Element seq -> Bool) -> seq -> [seq] -- | Type class for maps whose keys can be converted into sets. class SetContainer set => HasKeysSet set where { -- | Type of the key set. type family KeySet set; } -- | Convert a map into a set of its keys. keysSet :: HasKeysSet set => set -> KeySet set -- | Type of the key set. type family KeySet set -- | Zip operations on MonoFunctors. class MonoFunctor mono => MonoZip mono -- | Combine each element of two MonoZips using a supplied function. ozipWith :: MonoZip mono => (Element mono -> Element mono -> Element mono) -> mono -> mono -> mono -- | Take two MonoZips and return a list of the pairs of their -- elements. ozip :: MonoZip mono => mono -> mono -> [(Element mono, Element mono)] -- | Take a list of pairs of elements and return a MonoZip of the -- first components and a MonoZip of the second components. ounzip :: MonoZip mono => [(Element mono, Element mono)] -> (mono, mono) -- | Polymorphic typeclass for interacting with different set types class (SetContainer set, Element set ~ ContainerKey set) => IsSet set -- | Insert a value into a set. insertSet :: IsSet set => Element set -> set -> set -- | Delete a value from a set. deleteSet :: IsSet set => Element set -> set -> set -- | Create a set from a single element. singletonSet :: IsSet set => Element set -> set -- | Convert a list to a set. setFromList :: IsSet set => [Element set] -> set -- | Convert a set to a list. setToList :: IsSet set => set -> [Element set] -- | Filter values in a set. filterSet :: IsSet set => (Element set -> Bool) -> set -> set -- | Polymorphic typeclass for interacting with different map types class (MonoTraversable map, SetContainer map) => IsMap map where { -- | In some cases, MapValue and Element will be different, -- e.g., the IsMap instance of associated lists. type family MapValue map; } -- | Look up a value in a map with a specified key. lookup :: IsMap map => ContainerKey map -> map -> Maybe (MapValue map) -- | Insert a key-value pair into a map. insertMap :: IsMap map => ContainerKey map -> MapValue map -> map -> map -- | Delete a key-value pair of a map using a specified key. deleteMap :: IsMap map => ContainerKey map -> map -> map -- | Create a map from a single key-value pair. singletonMap :: IsMap map => ContainerKey map -> MapValue map -> map -- | Convert a list of key-value pairs to a map mapFromList :: IsMap map => [(ContainerKey map, MapValue map)] -> map -- | Convert a map to a list of key-value pairs. mapToList :: IsMap map => map -> [(ContainerKey map, MapValue map)] -- | Like lookup, but uses a default value when the key does not -- exist in the map. findWithDefault :: IsMap map => MapValue map -> ContainerKey map -> map -> MapValue map -- | Insert a key-value pair into a map. -- -- Inserts the value directly if the key does not exist in the map. -- Otherwise, apply a supplied function that accepts the new value and -- the previous value and insert that result into the map. insertWith :: IsMap map => (MapValue map -> MapValue map -> MapValue map) -> ContainerKey map -> MapValue map -> map -> map -- | Insert a key-value pair into a map. -- -- Inserts the value directly if the key does not exist in the map. -- Otherwise, apply a supplied function that accepts the key, the new -- value, and the previous value and insert that result into the map. insertWithKey :: IsMap map => (ContainerKey map -> MapValue map -> MapValue map -> MapValue map) -> ContainerKey map -> MapValue map -> map -> map -- | Insert a key-value pair into a map, return the previous key's value if -- it existed. -- -- Inserts the value directly if the key does not exist in the map. -- Otherwise, apply a supplied function that accepts the key, the new -- value, and the previous value and insert that result into the map. insertLookupWithKey :: IsMap map => (ContainerKey map -> MapValue map -> MapValue map -> MapValue map) -> ContainerKey map -> MapValue map -> map -> (Maybe (MapValue map), map) -- | Apply a function to the value of a given key. -- -- Returns the input map when the key-value pair does not exist. adjustMap :: IsMap map => (MapValue map -> MapValue map) -> ContainerKey map -> map -> map -- | Equivalent to adjustMap, but the function accepts the key, as -- well as the previous value. adjustWithKey :: IsMap map => (ContainerKey map -> MapValue map -> MapValue map) -> ContainerKey map -> map -> map -- | Apply a function to the value of a given key. -- -- If the function returns Nothing, this deletes the key-value -- pair. -- -- Returns the input map when the key-value pair does not exist. updateMap :: IsMap map => (MapValue map -> Maybe (MapValue map)) -> ContainerKey map -> map -> map -- | Equivalent to updateMap, but the function accepts the key, as -- well as the previous value. updateWithKey :: IsMap map => (ContainerKey map -> MapValue map -> Maybe (MapValue map)) -> ContainerKey map -> map -> map -- | Apply a function to the value of a given key. -- -- If the map does not contain the key this returns Nothing and -- the input map. -- -- If the map does contain the key but the function returns -- Nothing, this returns the previous value and the map with the -- key-value pair removed. -- -- If the map contains the key and the function returns a value, this -- returns the new value and the map with the key-value pair with the new -- value. updateLookupWithKey :: IsMap map => (ContainerKey map -> MapValue map -> Maybe (MapValue map)) -> ContainerKey map -> map -> (Maybe (MapValue map), map) -- | Update/Delete the value of a given key. -- -- Applies a function to previous value of a given key, if it results in -- Nothing delete the key-value pair from the map, otherwise -- replace the previous value with the new value. alterMap :: IsMap map => (Maybe (MapValue map) -> Maybe (MapValue map)) -> ContainerKey map -> map -> map -- | Combine two maps. -- -- When a key exists in both maps, apply a function to both of the values -- and use the result of that as the value of the key in the resulting -- map. unionWith :: IsMap map => (MapValue map -> MapValue map -> MapValue map) -> map -> map -> map unionWithKey :: IsMap map => (ContainerKey map -> MapValue map -> MapValue map -> MapValue map) -> map -> map -> map -- | Combine a list of maps. -- -- When a key exists in two different maps, apply a function to both of -- the values and use the result of that as the value of the key in the -- resulting map. unionsWith :: IsMap map => (MapValue map -> MapValue map -> MapValue map) -> [map] -> map -- | Apply a function over every key-value pair of a map. mapWithKey :: IsMap map => (ContainerKey map -> MapValue map -> MapValue map) -> map -> map -- | Apply a function over every key of a pair and run unionsWith -- over the results. omapKeysWith :: IsMap map => (MapValue map -> MapValue map -> MapValue map) -> (ContainerKey map -> ContainerKey map) -> map -> map -- | Filter values in a map. filterMap :: IsMap map => (MapValue map -> Bool) -> map -> map -- | In some cases, MapValue and Element will be different, -- e.g., the IsMap instance of associated lists. type family MapValue map -- | A Map type polymorphic in both its key and value. class () => BiPolyMap (map :: Type -> Type -> Type) where { type family BPMKeyConstraint (map :: Type -> Type -> Type) key; } mapKeysWith :: (BiPolyMap map, BPMKeyConstraint map k1, BPMKeyConstraint map k2) => (v -> v -> v) -> (k1 -> k2) -> map k1 v -> map k2 v type family BPMKeyConstraint (map :: Type -> Type -> Type) key -- | A guaranteed-polymorphic Map, which allows for more -- polymorphic versions of functions. class () => PolyMap (map :: Type -> Type) -- | Get the difference between two maps, using the left map's values. differenceMap :: PolyMap map => map value1 -> map value2 -> map value1 -- | Get the intersection of two maps, using the left map's values. intersectionMap :: PolyMap map => map value1 -> map value2 -> map value1 -- | Get the intersection of two maps with a supplied function that takes -- in the left map's value and the right map's value. intersectionWithMap :: PolyMap map => (value1 -> value2 -> value3) -> map value1 -> map value2 -> map value3 -- | A container whose values are stored in Key-Value pairs. class (Monoid set, Semigroup set, MonoFoldable set, Eq ContainerKey set, GrowingAppend set) => SetContainer set where { -- | The type of the key type family ContainerKey set; } -- | Check if there is a value with the supplied key in the container. member :: SetContainer set => ContainerKey set -> set -> Bool -- | Check if there isn't a value with the supplied key in the container. notMember :: SetContainer set => ContainerKey set -> set -> Bool -- | Get the union of two containers. union :: SetContainer set => set -> set -> set -- | Combine a collection of SetContainers, with left-most values -- overriding when there are matching keys. unions :: (SetContainer set, MonoFoldable mono, Element mono ~ set) => mono -> set -- | Get the difference of two containers. difference :: SetContainer set => set -> set -> set -- | Get the intersection of two containers. intersection :: SetContainer set => set -> set -> set -- | Get a list of all of the keys in the container. keys :: SetContainer set => set -> [ContainerKey set] -- | The type of the key type family ContainerKey set -- | A monomorphic container that is not null. data () => NonNull mono -- | A class for monads in which exceptions may be thrown. -- -- Instances should obey the following law: -- --
--   throwM e >> x = throwM e
--   
-- -- In other words, throwing an exception short-circuits the rest of the -- monadic computation. class Monad m => MonadThrow (m :: Type -> Type) -- | The class of monad transformers. For any monad m, the result -- t m should also be a monad, and lift should be a monad -- transformation from m to t m, i.e. it should satisfy -- the following laws: -- -- -- -- Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t -- m be a Monad is enforced by the implication constraint -- forall m. Monad m => Monad (t m) enabled by -- the QuantifiedConstraints extension. -- --

Ambiguity error with GHC 9.0 to 9.2.2

-- -- These versions of GHC have a bug -- (https://gitlab.haskell.org/ghc/ghc/-/issues/20582) which -- causes constraints like -- --
--   (MonadTrans t, forall m. Monad m => Monad (t m)) => ...
--   
-- -- to be reported as ambiguous. For transformers 0.6 and later, this can -- be fixed by removing the second constraint, which is implied by the -- first. class forall (m :: Type -> Type). Monad m => Monad t m => MonadTrans (t :: Type -> Type -> Type -> Type) -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | A method for acquiring a scarce resource, providing the means of -- freeing it when no longer needed. This data type provides -- Functor/Applicative/Monad instances for -- composing different resources together. You can allocate these -- resources using either the bracket pattern (via -- with) or using ResourceT (via -- allocateAcquire). -- -- This concept was originally introduced by Gabriel Gonzalez and -- described at: -- http://www.haskellforall.com/2013/06/the-resource-applicative.html. -- The implementation in this package is slightly different, due to -- taking a different approach to async exception safety. data () => Acquire a -- | The way in which a release is called. data () => ReleaseType ReleaseEarly :: ReleaseType ReleaseNormal :: ReleaseType ReleaseExceptionWith :: SomeException -> ReleaseType pattern ReleaseException :: ReleaseType -- | The Resource transformer. This transformer keeps track of all -- registered actions, and calls them upon exit (via -- runResourceT). Actions may be registered via -- register, or resources may be allocated atomically via -- allocate. allocate corresponds closely to -- bracket. -- -- Releasing may be performed before exit via the release -- function. This is a highly recommended optimization, as it will ensure -- that scarce resources are freed early. Note that calling -- release will deregister the action, so that a release action -- will only ever be called once. -- -- Since 0.3.0 data () => ResourceT (m :: Type -> Type) a -- | A Monad which allows for safe resource allocation. In theory, -- any monad transformer stack which includes a ResourceT can be -- an instance of MonadResource. -- -- Note: runResourceT has a requirement for a MonadUnliftIO -- m monad, which allows control operations to be lifted. A -- MonadResource does not have this requirement. This means that -- transformers such as ContT can be an instance of -- MonadResource. However, the ContT wrapper will need -- to be unwrapped before calling runResourceT. -- -- Since 0.3.0 class MonadIO m => MonadResource (m :: Type -> Type) -- | Lift a ResourceT IO action into the current Monad. -- -- Since 0.4.0 liftResourceT :: MonadResource m => ResourceT IO a -> m a -- | Provides an alternative Applicative instance for -- ConduitT. In this instance, every incoming value is provided -- to all ConduitTs, and output is coalesced together. Leftovers -- from individual ConduitTs will be used within that component, -- and then discarded at the end of their computation. Output and -- finalizers will both be handled in a left-biased manner. -- -- As an example, take the following program: -- --
--   main :: IO ()
--   main = do
--       let src = mapM_ yield [1..3 :: Int]
--           conduit1 = CL.map (+1)
--           conduit2 = CL.concatMap (replicate 2)
--           conduit = getZipConduit $ ZipConduit conduit1 <* ZipConduit conduit2
--           sink = CL.mapM_ print
--       src $$ conduit =$ sink
--   
-- -- It will produce the output: 2, 1, 1, 3, 2, 2, 4, 3, 3 -- -- Since 1.0.17 newtype () => ZipConduit i o (m :: Type -> Type) r ZipConduit :: ConduitT i o m r -> ZipConduit i o (m :: Type -> Type) r [getZipConduit] :: ZipConduit i o (m :: Type -> Type) r -> ConduitT i o m r -- | A wrapper for defining an Applicative instance for Sinks -- which allows to combine sinks together, generalizing zipSinks. -- A combined sink distributes the input to all its participants and when -- all finish, produces the result. This allows to define functions like -- --
--   sequenceSinks :: (Monad m)
--             => [ConduitT i Void m r] -> ConduitT i Void m [r]
--   sequenceSinks = getZipSink . sequenceA . fmap ZipSink
--   
-- -- Note that the standard Applicative instance for conduits works -- differently. It feeds one sink with input until it finishes, then -- switches to another, etc., and at the end combines their results. -- -- This newtype is in fact a type constrained version of -- ZipConduit, and has the same behavior. It's presented as a -- separate type since (1) it historically predates ZipConduit, -- and (2) the type constraining can make your code clearer (and thereby -- make your error messages more easily understood). -- -- Since 1.0.13 newtype () => ZipSink i (m :: Type -> Type) r ZipSink :: ConduitT i Void m r -> ZipSink i (m :: Type -> Type) r [getZipSink] :: ZipSink i (m :: Type -> Type) r -> ConduitT i Void m r -- | A wrapper for defining an Applicative instance for -- Sources which allows to combine sources together, generalizing -- zipSources. A combined source will take input yielded from each -- of its Sources until any of them stop producing output. -- -- Since 1.0.13 newtype () => ZipSource (m :: Type -> Type) o ZipSource :: ConduitT () o m () -> ZipSource (m :: Type -> Type) o [getZipSource] :: ZipSource (m :: Type -> Type) o -> ConduitT () o m () -- | Provide for a stream of data that can be flushed. -- -- A number of Conduits (e.g., zlib compression) need the -- ability to flush the stream at some point. This provides a single -- wrapper datatype to be used in all such circumstances. -- -- Since 0.3.0 data () => Flush a Chunk :: a -> Flush a Flush :: Flush a -- | A component which consumes a stream of input values and produces a -- final result, regardless of the output stream. A Consumer is -- a generalization of a Sink, and can be used as either a -- Sink or a Conduit. -- -- Since 1.0.0 type Consumer i (m :: Type -> Type) r = forall o. () => ConduitT i o m r -- | Consumes a stream of input values and produces a final result, without -- producing any output. -- --
--   type Sink i m r = ConduitT i Void m r
--   
-- -- Since 0.5.0 type Sink i = ConduitT i Void -- | A component which produces a stream of output values, regardless of -- the input stream. A Producer is a generalization of a -- Source, and can be used as either a Source or a -- Conduit. -- -- Since 1.0.0 type Producer (m :: Type -> Type) o = forall i. () => ConduitT i o m () -- | Provides a stream of output values, without consuming any input or -- producing a final result. -- -- Since 0.5.0 type Source (m :: Type -> Type) o = ConduitT () o m () -- | Same as ConduitT, for backwards compat type ConduitM = ConduitT -- | In order to provide for efficient monadic composition, the -- ConduitT type is implemented internally using a technique -- known as the codensity transform. This allows for cheap appending, but -- makes one case much more expensive: partially running a -- ConduitT and that capturing the new state. -- -- This data type is the same as ConduitT, but does not use the -- codensity transform technique. data () => SealedConduitT i o (m :: Type -> Type) r -- | Core datatype of the conduit package. This type represents a general -- component which can consume a stream of input values i, -- produce a stream of output values o, perform actions in the -- m monad, and produce a final result r. The type -- synonyms provided here are simply wrappers around this type. -- -- Since 1.3.0 data () => ConduitT i o (m :: Type -> Type) r -- | A buffer allocation strategy (buf0, nextBuf) specifies the -- initial buffer to use and how to compute a new buffer nextBuf -- minSize buf with at least size minSize from a filled -- buffer buf. The double nesting of the IO monad helps -- to ensure that the reference to the filled buffer buf is lost -- as soon as possible, but the new buffer doesn't have to be allocated -- too early. type BufferAllocStrategy = (IO Buffer, Int -> Buffer -> IO IO Buffer) -- | A class for types with a default value. class () => Default a -- | The default value for this type. def :: Default a => a -- | Status of streaming a request body from a file. -- -- Since 0.4.9 data () => StreamFileStatus StreamFileStatus :: Int64 -> Int64 -> Int -> StreamFileStatus [fileSize] :: StreamFileStatus -> Int64 [readSoFar] :: StreamFileStatus -> Int64 [thisChunkSize] :: StreamFileStatus -> Int class () => HasHttpManager a getHttpManager :: HasHttpManager a => a -> Manager -- | Keeps track of open connections for keep-alive. -- -- If possible, you should share a single Manager between multiple -- threads and requests. -- -- Since 0.1.0 data () => Manager -- | How the HTTP proxy server settings should be discovered. -- -- Since 0.4.7 data () => ProxyOverride -- | Settings for a Manager. Please use the -- defaultManagerSettings function and then modify individual -- settings. For more information, see -- http://www.yesodweb.com/book/settings-types. -- -- Since 0.1.0 data () => ManagerSettings -- | A simple representation of the HTTP response. -- -- Since 0.1.0 data () => Response body -- | How to deal with timing out on retrieval of response headers. data () => ResponseTimeout -- | All information on how to connect to a host and what should be sent in -- the HTTP request. -- -- If you simply wish to download from a URL, see parseRequest. -- -- The constructor for this data type is not exposed. Instead, you should -- use either the defaultRequest value, or parseRequest -- to construct from a URL, and then use the records below to make -- modifications. This approach allows http-client to add configuration -- options without breaking backwards compatibility. -- -- For example, to construct a POST request, you could do something like: -- --
--   initReq <- parseRequest "http://www.example.com/path"
--   let req = initReq
--               { method = "POST"
--               }
--   
-- -- For more information, please see -- http://www.yesodweb.com/book/settings-types. -- -- Since 0.1.0 data () => Request -- | A function which will provide a Popper to a NeedsPopper. -- This seemingly convoluted structure allows for creation of request -- bodies which allocate scarce resources in an exception safe manner. -- -- Since 0.1.0 type GivesPopper a = NeedsPopper a -> IO a -- | A function which must be provided with a Popper. -- -- Since 0.1.0 type NeedsPopper a = Popper -> IO a -- | A function which generates successive chunks of a request body, -- provider a single empty bytestring when no more data is available. -- -- Since 0.1.0 type Popper = IO ByteString -- | When using one of the RequestBodyStream / -- RequestBodyStreamChunked constructors, you must ensure that the -- GivesPopper can be called multiple times. Usually this is not a -- problem. -- -- The RequestBodyStreamChunked will send a chunked request body. -- Note that not all servers support this. Only use -- RequestBodyStreamChunked if you know the server you're sending -- to supports chunked request bodies. -- -- Since 0.1.0 data () => RequestBody RequestBodyLBS :: ByteString -> RequestBody RequestBodyBS :: ByteString -> RequestBody RequestBodyBuilder :: Int64 -> Builder -> RequestBody RequestBodyStream :: Int64 -> GivesPopper () -> RequestBody RequestBodyStreamChunked :: GivesPopper () -> RequestBody -- | Allows creation of a RequestBody inside the IO -- monad, which is useful for making easier APIs (like -- setRequestBodyFile). RequestBodyIO :: IO RequestBody -> RequestBody data () => CookieJar data () => Cookie Cookie :: ByteString -> ByteString -> UTCTime -> ByteString -> ByteString -> UTCTime -> UTCTime -> Bool -> Bool -> Bool -> Bool -> Cookie [cookie_name] :: Cookie -> ByteString [cookie_value] :: Cookie -> ByteString [cookie_expiry_time] :: Cookie -> UTCTime [cookie_domain] :: Cookie -> ByteString [cookie_path] :: Cookie -> ByteString [cookie_creation_time] :: Cookie -> UTCTime [cookie_last_access_time] :: Cookie -> UTCTime [cookie_persistent] :: Cookie -> Bool [cookie_host_only] :: Cookie -> Bool [cookie_secure_only] :: Cookie -> Bool [cookie_http_only] :: Cookie -> Bool data () => HttpExceptionContent -- | Generated by the parseUrlThrow function when the server -- returns a non-2XX response status code. -- -- May include the beginning of the response body. StatusCodeException :: Response () -> ByteString -> HttpExceptionContent -- | The server responded with too many redirects for a request. -- -- Contains the list of encountered responses containing redirects in -- reverse chronological order; including last redirect, which triggered -- the exception and was not followed. TooManyRedirects :: [Response ByteString] -> HttpExceptionContent -- | Either too many headers, or too many total bytes in a single header, -- were returned by the server, and the memory exhaustion protection in -- this library has kicked in. OverlongHeaders :: HttpExceptionContent -- | The server took too long to return a response. This can be altered via -- responseTimeout or managerResponseTimeout. ResponseTimeout :: HttpExceptionContent -- | Attempting to connect to the server timed out. ConnectionTimeout :: HttpExceptionContent -- | An exception occurred when trying to connect to the server. ConnectionFailure :: SomeException -> HttpExceptionContent -- | The status line returned by the server could not be parsed. InvalidStatusLine :: ByteString -> HttpExceptionContent -- | The given response header line could not be parsed InvalidHeader :: ByteString -> HttpExceptionContent -- | The given request header is not compliant (e.g. has newlines) InvalidRequestHeader :: ByteString -> HttpExceptionContent -- | An exception was raised by an underlying library when performing the -- request. Most often, this is caused by a failing socket action or a -- TLS exception. InternalException :: SomeException -> HttpExceptionContent -- | A non-200 status code was returned when trying to connect to the proxy -- server on the given host and port. ProxyConnectException :: ByteString -> Int -> Status -> HttpExceptionContent -- | No response data was received from the server at all. This exception -- may deserve special handling within the library, since it may indicate -- that a pipelining has been used, and a connection thought to be open -- was in fact closed. NoResponseDataReceived :: HttpExceptionContent -- | Exception thrown when using a Manager which does not have -- support for secure connections. Typically, you will want to use -- tlsManagerSettings from http-client-tls to overcome -- this. TlsNotSupported :: HttpExceptionContent -- | The request body provided did not match the expected size. -- -- Provides the expected and actual size. WrongRequestBodyStreamSize :: Word64 -> Word64 -> HttpExceptionContent -- | The returned response body is too short. Provides the expected size -- and actual size. ResponseBodyTooShort :: Word64 -> Word64 -> HttpExceptionContent -- | A chunked response body had invalid headers. InvalidChunkHeaders :: HttpExceptionContent -- | An incomplete set of response headers were returned. IncompleteHeaders :: HttpExceptionContent -- | The host we tried to connect to is invalid (e.g., an empty string). InvalidDestinationHost :: ByteString -> HttpExceptionContent -- | An exception was thrown when inflating a response body. HttpZlibException :: ZlibException -> HttpExceptionContent -- | Values in the proxy environment variable were invalid. Provides the -- environment variable name and its value. InvalidProxyEnvironmentVariable :: Text -> Text -> HttpExceptionContent -- | Attempted to use a Connection which was already closed ConnectionClosed :: HttpExceptionContent -- | Proxy settings are not valid (Windows specific currently) @since 0.5.7 InvalidProxySettings :: Text -> HttpExceptionContent -- | An exception which may be generated by this library data () => HttpException -- | Most exceptions are specific to a Request. Inspect the -- HttpExceptionContent value for details on what occurred. HttpExceptionRequest :: Request -> HttpExceptionContent -> HttpException -- | A URL (first field) is invalid for a given reason (second argument). InvalidUrlException :: String -> String -> HttpException -- | A datatype holding information on redirected requests and the final -- response. -- -- Since 0.4.1 data () => HistoriedResponse body -- | A list of Headers. -- -- Same type as RequestHeaders, but useful to differentiate in -- type signatures. type ResponseHeaders = [Header] -- | A list of Headers. -- -- Same type as ResponseHeaders, but useful to differentiate in -- type signatures. type RequestHeaders = [Header] -- | A sequence of QueryItems. type Query = [QueryItem] -- | An item from the query string, split up into two parts. -- -- The second part should be Nothing if there was no key-value -- separator after the query item name. type QueryItem = (ByteString, Maybe ByteString) -- | A list of byte ranges. type ByteRanges = [ByteRange] -- | An individual byte range. -- -- Negative indices are not allowed! data () => ByteRange ByteRangeFrom :: !Integer -> ByteRange ByteRangeFromTo :: !Integer -> !Integer -> ByteRange ByteRangeSuffix :: !Integer -> ByteRange -- | A case-insensitive name of a header field. -- -- This is the part of the header field before the colon: HeaderName: -- some value type HeaderName = CI ByteString -- | HTTP standard method (as defined by RFC 2616, and PATCH which is -- defined by RFC 5789). data () => StdMethod GET :: StdMethod POST :: StdMethod HEAD :: StdMethod PUT :: StdMethod DELETE :: StdMethod TRACE :: StdMethod CONNECT :: StdMethod OPTIONS :: StdMethod PATCH :: StdMethod -- | HTTP method (flat ByteString type). type Method = ByteString -- | HTTP Status. -- -- Only the statusCode is used for comparisons. -- -- Please use mkStatus to create status codes from code and -- message, or the Enum instance or the status code -- constants (like ok200). There might be additional record -- members in the future. -- -- Note that the Show instance is only for debugging. data () => Status Status :: Int -> ByteString -> Status [statusCode] :: Status -> Int [statusMessage] :: Status -> ByteString -- | Query with some characters that should not be escaped. -- -- General form: a=b&c=d:e+f&g=h type PartialEscapeQuery = [PartialEscapeQueryItem] -- | Partially escaped query item. -- -- The key will always be encoded using 'urlEncode True', but -- the value will be encoded depending on which EscapeItems are -- used. type PartialEscapeQueryItem = (ByteString, [EscapeItem]) -- | Section of a query item value that decides whether to use regular URL -- encoding (using 'urlEncode True') with QE, or to not -- encode anything with QN. data () => EscapeItem -- | will be URL encoded QE :: ByteString -> EscapeItem -- | will NOT at all be URL encoded QN :: ByteString -> EscapeItem -- | A sequence of SimpleQueryItems. type SimpleQuery = [SimpleQueryItem] -- | Simplified query item type without support for parameter-less items. type SimpleQueryItem = (ByteString, ByteString) -- | Like Query, but with Text instead of ByteString -- (UTF8-encoded). type QueryText = [(Text, Maybe Text)] -- | Types which can, and commonly are, converted to Query are in -- this class. -- -- You can use lists of simple key value pairs, with ByteString -- (strict, or lazy: ByteString), Text, or String as -- the key/value types. You can also have the value type lifted into a -- Maybe to support keys without values; and finally it is possible to -- put each pair into a Maybe for key-value pairs that aren't always -- present. class () => QueryLike a -- | Convert to Query. toQuery :: QueryLike a => a -> Query -- | HTTP Version. -- -- Note that the Show instance is intended merely for debugging. data () => HttpVersion HttpVersion :: !Int -> !Int -> HttpVersion [httpMajor] :: HttpVersion -> !Int [httpMinor] :: HttpVersion -> !Int -- | A Monad which has the ability to log messages in some manner. class Monad m => MonadLogger (m :: Type -> Type) data () => LogLevel LevelDebug :: LogLevel LevelInfo :: LogLevel LevelWarn :: LogLevel LevelError :: LogLevel LevelOther :: Text -> LogLevel class () => PathMultiPiece s fromPathMultiPiece :: PathMultiPiece s => [Text] -> Maybe s toPathMultiPiece :: PathMultiPiece s => s -> [Text] class () => PathPiece s fromPathPiece :: PathPiece s => Text -> Maybe s toPathPiece :: PathPiece s => s -> Text -- | Represents a value containing all the configuration options for a -- specific backend. This abstraction makes it easier to write code that -- can easily swap backends. class () => PersistConfig c where { type family PersistConfigBackend c :: Type -> Type -> Type -> Type; type family PersistConfigPool c; } -- | Load the config settings from a Value, most likely taken from a -- YAML config file. loadConfig :: PersistConfig c => Value -> Parser c -- | Modify the config settings based on environment variables. applyEnv :: PersistConfig c => c -> IO c -- | Create a new connection pool based on the given config settings. createPoolConfig :: PersistConfig c => c -> IO (PersistConfigPool c) -- | Run a database action by taking a connection from the pool. runPool :: (PersistConfig c, MonadUnliftIO m) => c -> PersistConfigBackend c m a -> PersistConfigPool c -> m a type family PersistConfigBackend c :: Type -> Type -> Type -> Type type family PersistConfigPool c -- | An ConstraintNameHS represents the Haskell-side name that -- persistent will use for a constraint. newtype () => ConstraintNameHS ConstraintNameHS :: Text -> ConstraintNameHS [unConstraintNameHS] :: ConstraintNameHS -> Text -- | A ConstraintNameDB represents the datastore-side name that -- persistent will use for a constraint. newtype () => ConstraintNameDB ConstraintNameDB :: Text -> ConstraintNameDB [unConstraintNameDB] :: ConstraintNameDB -> Text -- | An EntityNameDB represents the datastore-side name that -- persistent will use for an entity. newtype () => EntityNameDB EntityNameDB :: Text -> EntityNameDB [unEntityNameDB] :: EntityNameDB -> Text -- | An EntityNameHS represents the Haskell-side name that -- persistent will use for an entity. newtype () => EntityNameHS EntityNameHS :: Text -> EntityNameHS [unEntityNameHS] :: EntityNameHS -> Text -- | A FieldNameHS represents the Haskell-side name that -- persistent will use for a field. newtype () => FieldNameHS FieldNameHS :: Text -> FieldNameHS [unFieldNameHS] :: FieldNameHS -> Text -- | A FieldNameDB represents the datastore-side name that -- persistent will use for a field. newtype () => FieldNameDB FieldNameDB :: Text -> FieldNameDB [unFieldNameDB] :: FieldNameDB -> Text -- | Convenience operations for working with '-NameDB' types. class () => DatabaseName a escapeWith :: DatabaseName a => (Text -> str) -> a -> str -- | A type that determines how a backend should handle the literal. data () => LiteralType -- | The accompanying value will be escaped before inserting into the -- database. This is the correct default choice to use. Escaped :: LiteralType -- | The accompanying value will not be escaped when inserting into the -- database. This is potentially dangerous - use this with care. Unescaped :: LiteralType -- | The DbSpecific constructor corresponds to the legacy -- PersistDbSpecific constructor. We need to keep this around -- because old databases may have serialized JSON representations that -- reference this. We don't want to break the ability of a database to -- load rows. DbSpecific :: LiteralType -- | A raw value which can be stored in any backend and can be marshalled -- to and from a PersistField. data () => PersistValue PersistText :: Text -> PersistValue PersistByteString :: ByteString -> PersistValue PersistInt64 :: Int64 -> PersistValue PersistDouble :: Double -> PersistValue PersistRational :: Rational -> PersistValue PersistBool :: Bool -> PersistValue PersistDay :: Day -> PersistValue PersistTimeOfDay :: TimeOfDay -> PersistValue PersistUTCTime :: UTCTime -> PersistValue PersistNull :: PersistValue PersistList :: [PersistValue] -> PersistValue PersistMap :: [(Text, PersistValue)] -> PersistValue -- | Intended especially for MongoDB backend PersistObjectId :: ByteString -> PersistValue -- | Intended especially for PostgreSQL backend for text arrays PersistArray :: [PersistValue] -> PersistValue -- | This constructor is used to specify some raw literal value for the -- backend. The LiteralType value specifies how the value should -- be escaped. This can be used to make special, custom types avaialable -- in the back end. PersistLiteral_ :: LiteralType -> ByteString -> PersistValue -- | This pattern synonym used to be a data constructor on -- PersistValue, but was changed into a catch-all pattern synonym -- to allow backwards compatiblity with database types. See the -- documentation on PersistDbSpecific for more details. pattern PersistLiteral :: ByteString -> PersistValue -- | This pattern synonym used to be a data constructor on -- PersistValue, but was changed into a catch-all pattern synonym -- to allow backwards compatiblity with database types. See the -- documentation on PersistDbSpecific for more details. pattern PersistLiteralEscaped :: ByteString -> PersistValue -- | This pattern synonym used to be a data constructor for the -- PersistValue type. It was changed to be a pattern so that -- JSON-encoded database values could be parsed into their corresponding -- values. You should not use this, and instead prefer to pattern match -- on PersistLiteral_ directly. -- -- If you use this, it will overlap a patern match on the -- 'PersistLiteral_, PersistLiteral, and -- PersistLiteralEscaped patterns. If you need to disambiguate -- between these constructors, pattern match on PersistLiteral_ -- directly. pattern PersistDbSpecific :: ByteString -> PersistValue -- | A FieldDef represents the inormation that persistent -- knows about a field of a datatype. This includes information used to -- parse the field out of the database and what the field corresponds to. data () => FieldDef FieldDef :: !FieldNameHS -> !FieldNameDB -> !FieldType -> !SqlType -> ![FieldAttr] -> !Bool -> !ReferenceDef -> !FieldCascade -> !Maybe Text -> !Maybe Text -> !Bool -> FieldDef -- | The name of the field. Note that this does not corresponds to the -- record labels generated for the particular entity - record labels are -- generated with the type name prefixed to the field, so a -- FieldDef that contains a FieldNameHS "name" for -- a type User will have a record field userName. [fieldHaskell] :: FieldDef -> !FieldNameHS -- | The name of the field in the database. For SQL databases, this -- corresponds to the column name. [fieldDB] :: FieldDef -> !FieldNameDB -- | The type of the field in Haskell. [fieldType] :: FieldDef -> !FieldType -- | The type of the field in a SQL database. [fieldSqlType] :: FieldDef -> !SqlType -- | User annotations for a field. These are provided with the ! -- operator. [fieldAttrs] :: FieldDef -> ![FieldAttr] -- | If this is True, then the Haskell datatype will have a strict -- record field. The default value for this is True. [fieldStrict] :: FieldDef -> !Bool [fieldReference] :: FieldDef -> !ReferenceDef -- | Defines how operations on the field cascade on to the referenced -- tables. This doesn't have any meaning if the fieldReference is -- set to NoReference or SelfReference. The cascade option -- here should be the same as the one obtained in the -- fieldReference. [fieldCascade] :: FieldDef -> !FieldCascade -- | Optional comments for a Field. [fieldComments] :: FieldDef -> !Maybe Text -- | Whether or not the field is a GENERATED column, and -- additionally the expression to use for generation. [fieldGenerated] :: FieldDef -> !Maybe Text -- | True if the field is an implicit ID column. False -- otherwise. [fieldIsImplicitIdColumn] :: FieldDef -> !Bool data () => PersistUpdate Assign :: PersistUpdate Add :: PersistUpdate Subtract :: PersistUpdate Multiply :: PersistUpdate Divide :: PersistUpdate BackendSpecificUpdate :: Text -> PersistUpdate type family BackendSpecificUpdate backend record data () => UpdateException KeyNotFound :: String -> UpdateException UpsertError :: String -> UpdateException data () => PersistFilter Eq :: PersistFilter Ne :: PersistFilter Gt :: PersistFilter Lt :: PersistFilter Ge :: PersistFilter Le :: PersistFilter In :: PersistFilter NotIn :: PersistFilter BackendSpecificFilter :: Text -> PersistFilter type family BackendSpecificFilter backend record -- | A SQL data type. Naming attempts to reflect the underlying Haskell -- datatypes, eg SqlString instead of SqlVarchar. Different SQL databases -- may have different translations for these types. data () => SqlType SqlString :: SqlType SqlInt32 :: SqlType SqlInt64 :: SqlType SqlReal :: SqlType SqlNumeric :: Word32 -> Word32 -> SqlType SqlBool :: SqlType SqlDay :: SqlType SqlTime :: SqlType -- | Always uses UTC timezone SqlDayTime :: SqlType SqlBlob :: SqlType -- | a backend-specific name SqlOther :: Text -> SqlType data () => PersistException -- | Generic Exception PersistError :: Text -> PersistException PersistMarshalError :: Text -> PersistException PersistInvalidField :: Text -> PersistException PersistForeignConstraintUnmet :: Text -> PersistException PersistMongoDBError :: Text -> PersistException PersistMongoDBUnsupported :: Text -> PersistException -- | An action that might happen on a deletion or update on a foreign key -- change. data () => CascadeAction Cascade :: CascadeAction Restrict :: CascadeAction SetNull :: CascadeAction SetDefault :: CascadeAction -- | This datatype describes how a foreign reference field cascades deletes -- or updates. -- -- This type is used in both parsing the model definitions and performing -- migrations. A Nothing in either of the field values means that -- the user has not specified a CascadeAction. An unspecified -- CascadeAction is defaulted to Restrict when doing -- migrations. data () => FieldCascade FieldCascade :: !Maybe CascadeAction -> !Maybe CascadeAction -> FieldCascade [fcOnUpdate] :: FieldCascade -> !Maybe CascadeAction [fcOnDelete] :: FieldCascade -> !Maybe CascadeAction data () => ForeignDef ForeignDef :: !EntityNameHS -> !EntityNameDB -> !ConstraintNameHS -> !ConstraintNameDB -> !FieldCascade -> ![(ForeignFieldDef, ForeignFieldDef)] -> ![Attr] -> Bool -> Bool -> ForeignDef [foreignRefTableHaskell] :: ForeignDef -> !EntityNameHS [foreignRefTableDBName] :: ForeignDef -> !EntityNameDB [foreignConstraintNameHaskell] :: ForeignDef -> !ConstraintNameHS [foreignConstraintNameDBName] :: ForeignDef -> !ConstraintNameDB -- | Determine how the field will cascade on updates and deletions. [foreignFieldCascade] :: ForeignDef -> !FieldCascade [foreignFields] :: ForeignDef -> ![(ForeignFieldDef, ForeignFieldDef)] [foreignAttrs] :: ForeignDef -> ![Attr] [foreignNullable] :: ForeignDef -> Bool -- | Determines if the reference is towards a Primary Key or not. [foreignToPrimary] :: ForeignDef -> Bool -- | Used instead of FieldDef to generate a smaller amount of code type ForeignFieldDef = (FieldNameHS, FieldNameDB) data () => CompositeDef CompositeDef :: !NonEmpty FieldDef -> ![Attr] -> CompositeDef [compositeFields] :: CompositeDef -> !NonEmpty FieldDef [compositeAttrs] :: CompositeDef -> ![Attr] -- | Type for storing the Uniqueness constraint in the Schema. Assume you -- have the following schema with a uniqueness constraint: -- --
--   Person
--     name String
--     age Int
--     UniqueAge age
--   
-- -- This will be represented as: -- --
--   UniqueDef
--       { uniqueHaskell = ConstraintNameHS (packPTH UniqueAge)
--       , uniqueDBName = ConstraintNameDB (packPTH "unique_age")
--       , uniqueFields = [(FieldNameHS (packPTH "age"), FieldNameDB (packPTH "age"))]
--       , uniqueAttrs = []
--       }
--   
data () => UniqueDef UniqueDef :: !ConstraintNameHS -> !ConstraintNameDB -> !NonEmpty (FieldNameHS, FieldNameDB) -> ![Attr] -> UniqueDef [uniqueHaskell] :: UniqueDef -> !ConstraintNameHS [uniqueDBName] :: UniqueDef -> !ConstraintNameDB [uniqueFields] :: UniqueDef -> !NonEmpty (FieldNameHS, FieldNameDB) [uniqueAttrs] :: UniqueDef -> ![Attr] -- | An EmbedFieldDef is the same as a FieldDef But it is only used for -- embeddedFields so it only has data needed for embedding data () => EmbedFieldDef EmbedFieldDef :: FieldNameDB -> Maybe (Either SelfEmbed EntityNameHS) -> EmbedFieldDef [emFieldDB] :: EmbedFieldDef -> FieldNameDB [emFieldEmbed] :: EmbedFieldDef -> Maybe (Either SelfEmbed EntityNameHS) -- | An EmbedEntityDef is the same as an EntityDef But it is only used for -- fieldReference so it only has data needed for embedding data () => EmbedEntityDef EmbedEntityDef :: EntityNameHS -> [EmbedFieldDef] -> EmbedEntityDef [embeddedHaskell] :: EmbedEntityDef -> EntityNameHS [embeddedFields] :: EmbedEntityDef -> [EmbedFieldDef] -- | There are 3 kinds of references 1) composite (to fields that exist in -- the record) 2) single field 3) embedded data () => ReferenceDef NoReference :: ReferenceDef -- | A ForeignRef has a late binding to the EntityDef it references via -- name and has the Haskell type of the foreign key in the form of -- FieldType ForeignRef :: !EntityNameHS -> ReferenceDef EmbedRef :: EntityNameHS -> ReferenceDef -- | A SelfReference stops an immediate cycle which causes non-termination -- at compile-time (issue #311). SelfReference :: ReferenceDef -- | A FieldType describes a field parsed from the QuasiQuoter and -- is used to determine the Haskell type in the generated code. -- -- name Text parses into FTTypeCon Nothing Text -- -- name T.Text parses into FTTypeCon (Just T -- Text) -- -- name (Jsonb User) parses into: -- --
--   FTApp (FTTypeCon Nothing Jsonb) (FTTypeCon Nothing User)
--   
data () => FieldType -- | Optional module and name. FTTypeCon :: Maybe Text -> Text -> FieldType FTLit :: FieldTypeLit -> FieldType FTTypePromoted :: Text -> FieldType FTApp :: FieldType -> FieldType -> FieldType FTList :: FieldType -> FieldType -- | Attributes that may be attached to fields that can affect migrations -- and serialization in backend-specific ways. -- -- While we endeavor to, we can't forsee all use cases for all backends, -- and so FieldAttr is extensible through its constructor -- FieldAttrOther. data () => FieldAttr -- | The Maybe keyword goes after the type. This indicates that the -- column is nullable, and the generated Haskell code will have a -- Maybe type for it. -- -- Example: -- --
--   User
--       name Text Maybe
--   
FieldAttrMaybe :: FieldAttr -- | This indicates that the column is nullable, but should not have a -- Maybe type. For this to work out, you need to ensure that the -- PersistField instance for the type in question can support a -- PersistNull value. -- --
--   data What = NoWhat | Hello Text
--   
--   instance PersistField What where
--       fromPersistValue PersistNull =
--           pure NoWhat
--       fromPersistValue pv =
--           Hello $ fromPersistValue pv
--   
--   instance PersistFieldSql What where
--       sqlType _ = SqlString
--   
--   User
--       what What nullable
--   
FieldAttrNullable :: FieldAttr -- | This tag means that the column will not be present on the Haskell -- code, but will not be removed from the database. Useful to deprecate -- fields in phases. -- -- You should set the column to be nullable in the database. Otherwise, -- inserts won't have values. -- --
--   User
--       oldName Text MigrationOnly
--       newName Text
--   
FieldAttrMigrationOnly :: FieldAttr -- | A SafeToRemove attribute is not present on the Haskell -- datatype, and the backend migrations should attempt to drop the column -- without triggering any unsafe migration warnings. -- -- Useful after you've used MigrationOnly to remove a column -- from the database in phases. -- --
--   User
--       oldName Text SafeToRemove
--       newName Text
--   
FieldAttrSafeToRemove :: FieldAttr -- | This attribute indicates that we should not create a foreign key -- reference from a column. By default, persistent will try and -- create a foreign key reference for a column if it can determine that -- the type of the column is a Key entity or an -- EntityId and the Entity's name was present in -- mkPersist. -- -- This is useful if you want to use the explicit foreign key syntax. -- --
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId      noreference
--       Foreign Post fk_comment_post postId
--   
FieldAttrNoreference :: FieldAttr -- | This is set to specify precisely the database table the column refers -- to. -- --
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId references="post"
--   
-- -- You should not need this - persistent should be capable of -- correctly determining the target table's name. If you do need this, -- please file an issue describing why. FieldAttrReference :: Text -> FieldAttr -- | Specify a name for the constraint on the foreign key reference for -- this table. -- --
--   Post
--       title    Text
--   
--   Comment
--       postId   PostId constraint="my_cool_constraint_name"
--   
FieldAttrConstraint :: Text -> FieldAttr -- | Specify the default value for a column. -- --
--   User
--       createdAt    UTCTime     default="NOW()"
--   
-- -- Note that a default= attribute does not mean you can omit the -- value while inserting. FieldAttrDefault :: Text -> FieldAttr -- | Specify a custom SQL type for the column. Generally, you should define -- a custom datatype with a custom PersistFieldSql instance -- instead of using this. -- --
--   User
--       uuid     Text    sqltype=UUID
--   
FieldAttrSqltype :: Text -> FieldAttr -- | Set a maximum length for a column. Useful for VARCHAR and indexes. -- --
--   User
--       name     Text    maxlen=200
--   
--       UniqueName name
--   
FieldAttrMaxlen :: Integer -> FieldAttr -- | Specify the database name of the column. -- --
--   User
--       blarghle     Int     sql="b_l_a_r_g_h_l_e"
--   
-- -- Useful for performing phased migrations, where one column is renamed -- to another column over time. FieldAttrSql :: Text -> FieldAttr -- | A grab bag of random attributes that were unrecognized by the parser. FieldAttrOther :: Text -> FieldAttr type Attr = Text type ExtraLine = [Text] -- | The definition for the entity's primary key ID. data () => EntityIdDef -- | The entity has a single key column, and it is a surrogate key - that -- is, you can't go from rec -> Key rec. EntityIdField :: !FieldDef -> EntityIdDef -- | The entity has a natural key. This means you can write rec -> -- Key rec because all the key fields are present on the datatype. -- -- A natural key can have one or more columns. EntityIdNaturalKey :: !CompositeDef -> EntityIdDef -- | An EntityDef represents the information that -- persistent knows about an Entity. It uses this information to -- generate the Haskell datatype, the SQL migrations, and other relevant -- conversions. data () => EntityDef -- | The reason why a field is nullable is very important. A field -- that is nullable because of a Maybe tag will have its type -- changed from A to Maybe A. OTOH, a field that is -- nullable because of a nullable tag will remain with the same -- type. data () => WhyNullable ByMaybeAttr :: WhyNullable ByNullableAttr :: WhyNullable data () => IsNullable Nullable :: !WhyNullable -> IsNullable NotNullable :: IsNullable -- | A Checkmark should be used as a field type whenever a -- uniqueness constraint should guarantee that a certain kind of record -- may appear at most once, but other kinds of records may appear any -- number of times. -- -- NOTE: You need to mark any Checkmark fields as -- nullable (see the following example). -- -- For example, suppose there's a Location entity that -- represents where a user has lived: -- --
--   Location
--       user    UserId
--       name    Text
--       current Checkmark nullable
--   
--       UniqueLocation user current
--   
-- -- The UniqueLocation constraint allows any number of -- Inactive Locations to be current. However, -- there may be at most one current Location per user -- (i.e., either zero or one per user). -- -- This data type works because of the way that SQL treats -- NULLable fields within uniqueness constraints. The SQL -- standard says that NULL values should be considered -- different, so we represent Inactive as SQL NULL, thus -- allowing any number of Inactive records. On the other hand, we -- represent Active as TRUE, so the uniqueness constraint -- will disallow more than one Active record. -- -- Note: There may be DBMSs that do not respect the SQL standard's -- treatment of NULL values on uniqueness constraints, please -- check if this data type works before relying on it. -- -- The SQL BOOLEAN type is used because it's the smallest data -- type available. Note that we never use FALSE, just -- TRUE and NULL. Provides the same behavior Maybe -- () would if () was a valid PersistField. data () => Checkmark -- | When used on a uniqueness constraint, there may be at most one -- Active record. Active :: Checkmark -- | When used on a uniqueness constraint, there may be any number of -- Inactive records. Inactive :: Checkmark -- | Prior to persistent-2.11.0, we provided an instance of -- PersistField for the Natural type. This was in error, -- because Natural represents an infinite value, and databases -- don't have reasonable types for this. -- -- The instance for Natural used the Int64 underlying type, -- which will cause underflow and overflow errors. This type has the -- exact same code in the instances, and will work seamlessly. -- -- A more appropriate type for this is the Word series of types -- from Data.Word. These have a bounded size, are guaranteed to be -- non-negative, and are quite efficient for the database to store. newtype () => OverflowNatural OverflowNatural :: Natural -> OverflowNatural [unOverflowNatural] :: OverflowNatural -> Natural -- | This class teaches Persistent how to take a custom type and marshal it -- to and from a PersistValue, allowing it to be stored in a -- database. -- --

Examples

-- --
Simple Newtype
-- -- You can use newtype to add more type safety/readability to a -- basis type like ByteString. In these cases, just derive -- PersistField and PersistFieldSql: -- --
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   
--   newtype HashedPassword = HashedPassword ByteString
--     deriving (Eq, Show, PersistField, PersistFieldSql)
--   
-- --
Smart Constructor Newtype
-- -- In this example, we create a PersistField instance for a -- newtype following the "Smart Constructor" pattern. -- --
--   {-# LANGUAGE GeneralizedNewtypeDeriving #-}
--   import qualified Data.Text as T
--   import qualified Data.Char as C
--   
--   -- | An American Social Security Number
--   newtype SSN = SSN ErrorMessage
--    deriving (Eq, Show, PersistFieldSql)
--   
--   mkSSN :: ErrorMessage -> Either ErrorMessage SSN
--   mkSSN t = if (T.length t == 9) && (T.all C.isDigit t)
--    then Right $ SSN t
--    else Left $ "Invalid SSN: " <> t
--   
--   instance PersistField SSN where
--     toPersistValue (SSN t) = PersistText t
--     fromPersistValue (PersistText t) = mkSSN t
--     -- Handle cases where the database does not give us PersistText
--     fromPersistValue x = Left $ "File.hs: When trying to deserialize an SSN: expected PersistText, received: " <> T.pack (show x)
--   
-- -- Tips: -- -- class () => PersistField a toPersistValue :: PersistField a => a -> PersistValue fromPersistValue :: PersistField a => PersistValue -> Either Text a -- | A type class which is used to witness that a type is safe to insert -- into the database without providing a primary key. -- -- The TemplateHaskell function mkPersist will generate -- instances of this class for any entity that it works on. If the entity -- has a default primary key, then it provides a regular instance. If the -- entity has a Primary natural key, then this works fine. But -- if the entity has an Id column with no default=, -- then this does a TypeError and forces the user to use -- insertKey. class () => SafeToInsert a -- | This type class is used with the OverloadedLabels extension -- to provide a more convenient means of using the EntityField -- type. EntityField definitions are prefixed with the type name -- to avoid ambiguity, but this ambiguity can result in verbose code. -- -- If you have a table User with a name Text field, -- then the corresponding EntityField is UserName. With -- this, we can write #name :: EntityField User Text. -- -- What's more fun is that the type is more general: it's actually -- #name :: (SymbolToField "name" rec typ) => EntityField rec -- typ -- -- Which means it is *polymorphic* over the actual record. This allows -- you to write code that can be generic over the tables, provided they -- have the right fields. class () => SymbolToField (sym :: Symbol) rec typ | sym rec -> typ symbolToField :: SymbolToField sym rec typ => EntityField rec typ -- | Datatype that represents an entity, with both its Key and its -- Haskell record representation. -- -- When using a SQL-based backend (such as SQLite or PostgreSQL), an -- Entity may take any number of columns depending on how many -- fields it has. In order to reconstruct your entity on the Haskell -- side, persistent needs all of your entity columns and in the -- right order. Note that you don't need to worry about this when using -- persistent's API since everything is handled correctly behind -- the scenes. -- -- However, if you want to issue a raw SQL command that returns an -- Entity, then you have to be careful with the column order. -- While you could use SELECT Entity.* WHERE ... and that would -- work most of the time, there are times when the order of the columns -- on your database is different from the order that persistent -- expects (for example, if you add a new field in the middle of you -- entity definition and then use the migration code -- -- persistent will expect the column to be in the middle, but -- your DBMS will put it as the last column). So, instead of using a -- query like the one above, you may use rawSql (from the -- Database.Persist.Sql module) with its /entity selection -- placeholder/ (a double question mark ??). Using -- rawSql the query above must be written as SELECT ?? WHERE -- ... Then rawSql will replace ?? with the list -- of all columns that we need from your entity in the right order. If -- your query returns two entities (i.e. (Entity backend a, Entity -- backend b)), then you must you use SELECT ??, ?? WHERE -- ..., and so on. data () => Entity record Entity :: Key record -> record -> Entity record [entityKey] :: Entity record -> Key record [entityVal] :: Entity record -> record -- | Value to filter with. Highly dependant on the type of filter used. data () => FilterValue typ [FilterValue] :: forall typ. typ -> FilterValue typ [FilterValues] :: forall typ. [typ] -> FilterValue typ [UnsafeValue] :: forall a typ. PersistField a => a -> FilterValue typ -- | Filters which are available for select, updateWhere -- and deleteWhere. Each filter constructor specifies the field -- being filtered on, the type of comparison applied (equals, not equals, -- etc) and the argument for the comparison. -- -- Persistent users use combinators to create these. -- -- Note that it's important to be careful about the PersistFilter -- that you are using, if you use this directly. For example, using the -- In PersistFilter requires that you have an array- or -- list-shaped EntityField. It is possible to construct values -- using this that will create malformed runtime values. data () => Filter record Filter :: EntityField record typ -> FilterValue typ -> PersistFilter -> Filter record [filterField] :: Filter record -> EntityField record typ [filterValue] :: Filter record -> FilterValue typ [filterFilter] :: Filter record -> PersistFilter -- | convenient for internal use, not needed for the API FilterAnd :: [Filter record] -> Filter record FilterOr :: [Filter record] -> Filter record BackendFilter :: BackendSpecificFilter (PersistEntityBackend record) record -> Filter record -- | Query options. -- -- Persistent users use these directly. data () => SelectOpt record Asc :: EntityField record typ -> SelectOpt record Desc :: EntityField record typ -> SelectOpt record OffsetBy :: Int -> SelectOpt record LimitTo :: Int -> SelectOpt record -- | Updating a database entity. -- -- Persistent users use combinators to create these. data () => Update record Update :: EntityField record typ -> typ -> PersistUpdate -> Update record [updateField] :: Update record -> EntityField record typ [updateValue] :: Update record -> typ [updateUpdate] :: Update record -> PersistUpdate BackendUpdate :: BackendSpecificUpdate (PersistEntityBackend record) record -> Update record -- | Persistent allows multiple different backends (databases). type family PersistEntityBackend record -- | An EntityField is parameterised by the Haskell record it -- belongs to and the additional type of that field. -- -- As of persistent-2.11.0.0, it's possible to use the -- OverloadedLabels language extension to refer to -- EntityField values polymorphically. See the documentation on -- SymbolToField for more information. data family EntityField record :: Type -> Type class (Show BackendKey backend, Read BackendKey backend, Eq BackendKey backend, Ord BackendKey backend, PersistStoreRead backend, PersistField BackendKey backend, ToJSON BackendKey backend, FromJSON BackendKey backend) => PersistStoreWrite backend -- | Create a new record in the database, returning an automatically -- created key (in SQL an auto-increment id). -- --

Example usage

-- -- Using schema-1 and dataset-1, let's insert a new user -- John. -- --
--   insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User)
--   insertJohn = insert $ User "John" 30
--   
-- --
--   johnId <- insertJohn
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   
insert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Key record) -- | Same as insert, but doesn't return a Key. -- --

Example usage

-- -- with schema-1 and dataset-1, -- --
--   insertJohn :: MonadIO m => ReaderT SqlBackend m (Key User)
--   insertJohn = insert_ $ User "John" 30
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   
insert_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m () -- | Create multiple records in the database and return their Keys. -- -- If you don't need the inserted Keys, use insertMany_. -- -- The MongoDB and PostgreSQL backends insert all records and retrieve -- their keys in one database query. -- -- The SQLite and MySQL backends use the slow, default implementation of -- mapM insert. -- --

Example usage

-- -- with schema-1 and dataset-1, -- --
--   insertUsers :: MonadIO m => ReaderT SqlBackend m [Key User]
--   insertUsers = insertMany [User "John" 30, User "Nick" 32, User "Jane" 20]
--   
-- --
--   userIds <- insertUsers
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   
insertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m [Key record] -- | Same as insertMany, but doesn't return any Keys. -- -- The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records -- in one database query. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   insertUsers_ :: MonadIO m => ReaderT SqlBackend m ()
--   insertUsers_ = insertMany_ [User "John" 30, User "Nick" 32, User "Jane" 20]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |John  |30   |
--   +-----+------+-----+
--   |4    |Nick  |32   |
--   +-----+------+-----+
--   |5    |Jane  |20   |
--   +-----+------+-----+
--   
insertMany_ :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m () -- | Same as insertMany_, but takes an Entity instead of just -- a record. -- -- Useful when migrating data from one entity to another and want to -- preserve ids. -- -- The MongoDB, PostgreSQL, SQLite and MySQL backends insert all records -- in one database query. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   insertUserEntityMany :: MonadIO m => ReaderT SqlBackend m ()
--   insertUserEntityMany = insertEntityMany [SnakeEntity, EvaEntity]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Snake |38   |
--   +-----+------+-----+
--   |4    |Eva   |38   |
--   +-----+------+-----+
--   
insertEntityMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => [Entity record] -> ReaderT backend m () -- | Create a new record in the database using the given key. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   insertAliceKey :: MonadIO m => Key User -> ReaderT SqlBackend m ()
--   insertAliceKey key = insertKey key $ User "Alice" 20
--   
-- --
--   insertAliceKey $ UserKey {unUserKey = SqlBackendKey {unSqlBackendKey = 3}}
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Alice |20   |
--   +-----+------+-----+
--   
insertKey :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () -- | Put the record in the database with the given key. Unlike -- replace, if a record with the given key does not exist then a -- new record will be inserted. -- --

Example usage

-- -- We try to explain upsertBy using schema-1 and -- dataset-1. -- -- First, we insert Philip to dataset-1. -- --
--   insertPhilip :: MonadIO m => ReaderT SqlBackend m (Key User)
--   insertPhilip = insert $ User "Philip" 42
--   
-- --
--   philipId <- insertPhilip
--   
-- -- This query will produce: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Philip|42   |
--   +-----+------+-----+
--   
-- --
--   repsertHaskell :: MonadIO m => Key record -> ReaderT SqlBackend m ()
--   repsertHaskell id = repsert id $ User "Haskell" 81
--   
-- --
--   repsertHaskell philipId
--   
-- -- This query will replace Philip's record with Haskell's one: -- --
--   +-----+-----------------+--------+
--   |id   |name             |age     |
--   +-----+-----------------+--------+
--   |1    |SPJ              |40      |
--   +-----+-----------------+--------+
--   |2    |Simon            |41      |
--   +-----+-----------------+--------+
--   |3    |Philip -> Haskell|42 -> 81|
--   +-----+-----------------+--------+
--   
-- -- repsert inserts the given record if the key doesn't exist. -- --
--   repsertXToUnknown :: MonadIO m => ReaderT SqlBackend m ()
--   repsertXToUnknown = repsert unknownId $ User "X" 999
--   
-- -- For example, applying the above query to dataset-1 will produce -- this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |X     |999  |
--   +-----+------+-----+
--   
repsert :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () -- | Put many entities into the database. -- -- Batch version of repsert for SQL backends. -- -- Useful when migrating data from one entity to another and want to -- preserve ids. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   repsertManyUsers :: MonadIO m =>ReaderT SqlBackend m ()
--   repsertManyusers = repsertMany [(simonId, User "Philip" 20), (unknownId999, User "Mr. X" 999)]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+----------------+---------+
--   |id   |name            |age      |
--   +-----+----------------+---------+
--   |1    |SPJ             |40       |
--   +-----+----------------+---------+
--   |2    |Simon -> Philip |41 -> 20 |
--   +-----+----------------+---------+
--   |999  |Mr. X           |999      |
--   +-----+----------------+---------+
--   
repsertMany :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => [(Key record, record)] -> ReaderT backend m () -- | Replace the record in the database with the given key. Note that the -- result is undefined if such record does not exist, so you must use -- insertKey or repsert in these cases. -- --

Example usage

-- -- With schema-1 schama-1 and dataset-1, -- --
--   replaceSpj :: MonadIO m => User -> ReaderT SqlBackend m ()
--   replaceSpj record = replace spjId record
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |Mike  |45   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   
replace :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> record -> ReaderT backend m () -- | Delete a specific record by identifier. Does nothing if record does -- not exist. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   deleteSpj :: MonadIO m => ReaderT SqlBackend m ()
--   deleteSpj = delete spjId
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   
delete :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m () -- | Update individual fields on a specific record. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   updateSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m ()
--   updateSpj updates = update spjId updates
--   
-- --
--   updateSpj [UserAge +=. 100]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |140  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   
update :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m () -- | Update individual fields on a specific record, and retrieve the -- updated value from the database. -- -- Note that this function will throw an exception if the given key is -- not found in the database. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   updateGetSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m User
--   updateGetSpj updates = updateGet spjId updates
--   
-- --
--   spj <- updateGetSpj [UserAge +=. 100]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |140  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   
updateGet :: forall record (m :: Type -> Type). (PersistStoreWrite backend, MonadIO m, PersistRecordBackend record backend) => Key record -> [Update record] -> ReaderT backend m record class (Show BackendKey backend, Read BackendKey backend, Eq BackendKey backend, Ord BackendKey backend, PersistCore backend, PersistField BackendKey backend, ToJSON BackendKey backend, FromJSON BackendKey backend) => PersistStoreRead backend -- | Get a record by identifier, if available. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   getSpj :: MonadIO m => ReaderT SqlBackend m (Maybe User)
--   getSpj = get spjId
--   
-- --
--   mspj <- getSpj
--   
-- -- The above query when applied on dataset-1, will get this: -- --
--   +------+-----+
--   | name | age |
--   +------+-----+
--   | SPJ  |  40 |
--   +------+-----+
--   
get :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => Key record -> ReaderT backend m (Maybe record) -- | Get many records by their respective identifiers, if available. -- --

Example usage

-- -- With schema-1 and dataset-1: -- --
--   getUsers :: MonadIO m => ReaderT SqlBackend m (Map (Key User) User)
--   getUsers = getMany allkeys
--   
-- --
--   musers <- getUsers
--   
-- -- The above query when applied on dataset-1, will get these -- records: -- --
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   
getMany :: forall record (m :: Type -> Type). (PersistStoreRead backend, MonadIO m, PersistRecordBackend record backend) => [Key record] -> ReaderT backend m (Map (Key record) record) class () => PersistCore backend where { data family BackendKey backend; } data family BackendKey backend -- | ToBackendKey converts a PersistEntity Key into a -- BackendKey This can be used by each backend to convert between -- a Key and a plain Haskell type. For Sql, that is done with -- toSqlKey and fromSqlKey. -- -- By default, a PersistEntity uses the default BackendKey -- for its Key and is an instance of ToBackendKey -- -- A Key that instead uses a custom type will not be an instance -- of ToBackendKey. class (PersistEntity record, PersistEntityBackend record ~ backend, PersistCore backend) => ToBackendKey backend record toBackendKey :: ToBackendKey backend record => Key record -> BackendKey backend fromBackendKey :: ToBackendKey backend record => BackendKey backend -> Key record -- | A convenient alias for common type signatures type PersistRecordBackend record backend = (PersistEntity record, PersistEntityBackend record ~ BaseBackend backend) -- | This class witnesses that two backend are compatible, and that you can -- convert from the sub backend into the sup backend. -- This is similar to the HasPersistBackend and -- IsPersistBackend classes, but where you don't want to fix the -- type associated with the PersistEntityBackend of a record. -- -- Generally speaking, where you might have: -- --
--   foo ::
--     ( PersistEntity record
--     , PersistEntityBackend record ~ BaseBackend backend
--     , IsSqlBackend backend
--     )
--   
-- -- this can be replaced with: -- --
--   foo ::
--     ( PersistEntity record,
--     , PersistEntityBackend record ~ backend
--     , BackendCompatible SqlBackend backend
--     )
--   
-- -- This works for SqlReadBackend because of the instance -- BackendCompatible SqlBackend -- SqlReadBackend, without needing to go through the -- BaseBackend type family. -- -- Likewise, functions that are currently hardcoded to use -- SqlBackend can be generalized: -- --
--   -- before:
--   asdf :: ReaderT SqlBackend m ()
--   asdf = pure ()
--   
--   -- after:
--   asdf' :: BackendCompatible SqlBackend backend => ReaderT backend m ()
--   asdf' = withCompatibleBackend asdf
--   
class () => BackendCompatible sup sub projectBackend :: BackendCompatible sup sub => sub -> sup -- | Class which witnesses that backend is essentially the same as -- BaseBackend backend. That is, they're isomorphic and -- backend is just some wrapper over BaseBackend -- backend. class HasPersistBackend backend => IsPersistBackend backend -- | Class which allows the plucking of a BaseBackend backend from -- some larger type. For example, instance HasPersistBackend -- (SqlReadBackend, Int) where type BaseBackend (SqlReadBackend, Int) = -- SqlBackend persistBackend = unSqlReadBackend . fst class () => HasPersistBackend backend where { type family BaseBackend backend; } persistBackend :: HasPersistBackend backend => backend -> BaseBackend backend type family BaseBackend backend -- | A SqlBackend represents a handle or connection to a database. -- It contains functions and values that allow databases to have more -- optimized implementations, as well as references that benefit -- performance and sharing. -- -- Instead of using the SqlBackend constructor directly, use the -- mkSqlBackend function. -- -- A SqlBackend is *not* thread-safe. You should not assume that a -- SqlBackend can be shared among threads and run concurrent -- queries. This *will* result in problems. Instead, you should create a -- Pool SqlBackend, known as a -- ConnectionPool, and pass that around in multi-threaded -- applications. -- -- To run actions in the persistent library, you should use the -- runSqlConn function. If you're using a multithreaded -- application, use the runSqlPool function. data () => SqlBackend -- | This class is used to ensure that functions requring at least one -- unique key are not called with records that have 0 unique keys. The -- quasiquoter automatically writes working instances for appropriate -- entities, and generates TypeError instances for records that -- have 0 unique keys. class PersistEntity record => AtLeastOneUniqueKey record requireUniquesP :: AtLeastOneUniqueKey record => record -> NonEmpty (Unique record) -- | This is an error message. It is used when an entity has multiple -- unique keys, and the function expects a single unique key. type MultipleUniqueKeysError ty = 'Text "The entity " ':<>: 'ShowType ty ':<>: 'Text " has multiple unique keys." ':$$: 'Text "The function you are trying to call requires only a single " ':<>: 'Text "unique key." ':$$: 'Text "There is probably a variant of the function with 'By' " ':<>: 'Text "appended that will allow you to select a unique key " ':<>: 'Text "for the operation." -- | This is an error message. It is used when writing instances of -- OnlyOneUniqueKey for an entity that has no unique keys. type NoUniqueKeysError ty = 'Text "The entity " ':<>: 'ShowType ty ':<>: 'Text " does not have any unique keys." ':$$: 'Text "The function you are trying to call requires a unique key " ':<>: 'Text "to be defined on the entity." -- | This class is used to ensure that upsert is only called on -- records that have a single Unique key. The quasiquoter -- automatically generates working instances for appropriate records, and -- generates TypeError instances for records that have 0 or -- multiple unique keys. class PersistEntity record => OnlyOneUniqueKey record onlyUniqueP :: OnlyOneUniqueKey record => record -> Unique record -- | Some functions in this module (insertUnique, insertBy, -- and replaceUnique) first query the unique indexes to check for -- conflicts. You could instead optimistically attempt to perform the -- operation (e.g. replace instead of replaceUnique). -- However, -- -- class (PersistUniqueRead backend, PersistStoreWrite backend) => PersistUniqueWrite backend -- | Delete a specific record by unique key. Does nothing if no record -- matches. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   deleteBySpjName :: MonadIO m => ReaderT SqlBackend m ()
--   deleteBySpjName = deleteBy UniqueUserName "SPJ"
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   
deleteBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m () -- | Like insert, but returns Nothing when the record -- couldn't be inserted because of a uniqueness constraint. -- --

Example usage

-- -- With schema-1 and dataset-1, we try to insert the -- following two records: -- --
--   linusId <- insertUnique $ User "Linus" 48
--   spjId   <- insertUnique $ User "SPJ" 90
--   
-- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   
-- -- Linus's record was inserted to dataset-1, while SPJ wasn't -- because SPJ already exists in dataset-1. insertUnique :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Key record)) -- | Same as insertUnique but doesn't return a Key. -- --

Example usage

-- -- With schema-1 and dataset-1, we try to insert the -- following two records: -- --
--   linusId <- insertUnique_ $ User "Linus" 48
--   spjId   <- insertUnique_ $ User "SPJ" 90
--   
-- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Linus |48   |
--   +-----+------+-----+
--   
-- -- Linus's record was inserted to dataset-1, while SPJ wasn't -- because SPJ already exists in dataset-1. insertUnique_ :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => record -> ReaderT backend m (Maybe ()) -- | Update based on a uniqueness constraint or insert: -- -- -- --

Example usage

-- -- First, we try to explain upsert using schema-1 and -- dataset-1. -- --
--   upsertSpj :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User))
--   upsertSpj updates = upsert (User "SPJ" 999) updates
--   
-- --
--   mSpjEnt <- upsertSpj [UserAge +=. 15]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -> 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   
-- --
--   upsertX :: MonadIO m => [Update User] -> ReaderT SqlBackend m (Maybe (Entity User))
--   upsertX updates = upsert (User "X" 999) updates
--   
-- --
--   mXEnt <- upsertX [UserAge +=. 15]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40      |
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   |3    |X    |999     |
--   +-----+-----+--------+
--   
-- -- Next, what if the schema has two uniqueness constraints? Let's check -- it out using schema-2: -- --
--   mSpjEnt <- upsertSpj [UserAge +=. 15]
--   
-- -- This fails with a compile-time type error alerting us to the fact that -- this record has multiple unique keys, and suggests that we look for -- upsertBy to select the unique key we want. upsert :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, OnlyOneUniqueKey record, SafeToInsert record) => record -> [Update record] -> ReaderT backend m (Entity record) -- | Update based on a given uniqueness constraint or insert: -- -- -- --

Example usage

-- -- We try to explain upsertBy using schema-2 and -- dataset-1. -- --
--   upsertBySpjName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
--   upsertBySpjName record updates = upsertBy (UniqueUserName "SPJ") record updates
--   
-- --
--   mSpjEnt <- upsertBySpjName (Person "X" 999) [PersonAge += .15]
--   
-- -- The above query will alter dataset-1 to: -- --
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -> 55|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   
-- --
--   upsertBySimonAge :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
--   upsertBySimonAge record updates = upsertBy (UniqueUserName "SPJ") record updates
--   
-- --
--   mPhilipEnt <- upsertBySimonAge (User "X" 999) [UserName =. "Philip"]
--   
-- -- The above query will alter dataset-1 to: -- --
--   +----+-----------------+-----+
--   | id |      name       | age |
--   +----+-----------------+-----+
--   |  1 | SPJ             |  40 |
--   +----+-----------------+-----+
--   |  2 | Simon -> Philip |  41 |
--   +----+-----------------+-----+
--   
-- --
--   upsertByUnknownName :: MonadIO m => User -> [Update User] -> ReaderT SqlBackend m (Entity User)
--   upsertByUnknownName record updates = upsertBy (UniqueUserName "Unknown") record updates
--   
-- --
--   mXEnt <- upsertByUnknownName (User "X" 999) [UserAge +=. 15]
--   
-- -- This query will alter dataset-1 to: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   |3    |X    |999  |
--   +-----+-----+-----+
--   
upsertBy :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => Unique record -> record -> [Update record] -> ReaderT backend m (Entity record) -- | Put many records into db -- -- putMany :: forall record (m :: Type -> Type). (PersistUniqueWrite backend, MonadIO m, PersistRecordBackend record backend, SafeToInsert record) => [record] -> ReaderT backend m () -- | Queries against Unique keys (other than the id Key). -- -- Please read the general Persistent documentation to learn how to -- create Unique keys. -- -- Using this with an Entity without a Unique key leads to undefined -- behavior. A few of these functions require a single -- Unique, so using an Entity with multiple Uniques is also -- undefined. In these cases persistent's goal is to throw an exception -- as soon as possible, but persistent is still transitioning to that. -- -- SQL backends automatically create uniqueness constraints, but for -- MongoDB you must manually place a unique index on a field to have a -- uniqueness constraint. class PersistStoreRead backend => PersistUniqueRead backend -- | Get a record by unique key, if available. Returns also the identifier. -- --

Example usage

-- -- With schema-1 and dataset-1: -- --
--   getBySpjName :: MonadIO m  => ReaderT SqlBackend m (Maybe (Entity User))
--   getBySpjName = getBy $ UniqueUserName "SPJ"
--   
-- --
--   mSpjEnt <- getBySpjName
--   
-- -- The above query when applied on dataset-1, will get this -- entity: -- --
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   
getBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m (Maybe (Entity record)) -- | Returns True if a record with this unique key exists, otherwise False. -- --

Example usage

-- -- With schema-1 and dataset-1: -- --
--   existsBySpjName :: MonadIO m  => ReaderT SqlBackend m Bool
--   existsBySpjName = existsBy $ UniqueUserName "SPJ"
--   
-- --
--   spjEntExists <- existsBySpjName
--   
-- -- The above query when applied on dataset-1, will return the -- value True. existsBy :: forall record (m :: Type -> Type). (PersistUniqueRead backend, MonadIO m, PersistRecordBackend record backend) => Unique record -> ReaderT backend m Bool -- | Backends supporting conditional write operations class (PersistQueryRead backend, PersistStoreWrite backend) => PersistQueryWrite backend -- | Update individual fields on any record matching the given criterion. updateWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [Update record] -> ReaderT backend m () -- | Delete all records matching the given criterion. deleteWhere :: forall (m :: Type -> Type) record. (PersistQueryWrite backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m () -- | Backends supporting conditional read operations. class (PersistCore backend, PersistStoreRead backend) => PersistQueryRead backend -- | Get all records matching the given criterion in the specified order. -- Returns also the identifiers. -- -- NOTE: This function returns an Acquire and a ConduitM, -- which implies that it streams from the database. It does not. Please -- use selectList to simplify the code. If you want streaming -- behavior, consider persistent-pagination which efficiently -- chunks a query into ranges, or investigate a backend-specific -- streaming solution. selectSourceRes :: forall record (m1 :: Type -> Type) (m2 :: Type -> Type). (PersistQueryRead backend, PersistRecordBackend record backend, MonadIO m1, MonadIO m2) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Entity record) m2 ())) -- | Get just the first record for the criterion. selectFirst :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m (Maybe (Entity record)) -- | Get the Keys of all records matching the given criterion. selectKeysRes :: forall (m1 :: Type -> Type) (m2 :: Type -> Type) record. (PersistQueryRead backend, MonadIO m1, MonadIO m2, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m1 (Acquire (ConduitM () (Key record) m2 ())) -- | The total number of records fulfilling the given criterion. count :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Int -- | Check if there is at least one record fulfilling the given criterion. exists :: forall (m :: Type -> Type) record. (PersistQueryRead backend, MonadIO m, PersistRecordBackend record backend) => [Filter record] -> ReaderT backend m Bool -- | A backwards-compatible alias for those that don't care about -- distinguishing between read and write queries. It signifies the -- assumption that, by default, a backend can write as well as read. type PersistStore a = PersistStoreWrite a -- | A backwards-compatible alias for those that don't care about -- distinguishing between read and write queries. It signifies the -- assumption that, by default, a backend can write as well as read. type PersistQuery a = PersistQueryWrite a -- | A backwards-compatible alias for those that don't care about -- distinguishing between read and write queries. It signifies the -- assumption that, by default, a backend can write as well as read. type PersistUnique a = PersistUniqueWrite a type SqlPersistT = ReaderT SqlBackend -- | A specification for how the implied ID columns are created. -- -- By default, persistent will give each table a default column -- named id (customizable by PersistSettings), and the -- column type will be whatever you'd expect from BackendKey -- yourBackendType. For The SqlBackend type, this is an -- auto incrementing integer primary key. -- -- You might want to give a different example. A common use case in -- postgresql is to use the UUID type, and automatically generate them -- using a SQL function. -- -- Previously, you'd need to add a custom Id annotation for each -- model. -- --
--   User
--       Id   UUID default="uuid_generate_v1mc()"
--       name Text
--   
--   Dog
--       Id   UUID default="uuid_generate_v1mc()"
--       name Text
--       user UserId
--   
-- -- Now, you can simply create an ImplicitIdDef that corresponds to -- this declaration. -- --
--   newtype UUID = UUID ByteString
--   
--   instance PersistField UUID where
--       toPersistValue (UUID bs) =
--           PersistLiteral_ Escaped bs
--       fromPersistValue pv =
--           case pv of
--               PersistLiteral_ Escaped bs ->
--                   Right (UUID bs)
--               _ ->
--                   Left "nope"
--   
--   instance PersistFieldSql UUID where
--       sqlType _ = SqlOther UUID
--   
-- -- With this instance at the ready, we can now create our implicit -- definition: -- --
--   uuidDef :: ImplicitIdDef
--   uuidDef = mkImplicitIdDef @UUID "uuid_generate_v1mc()"
--   
-- -- And we can use setImplicitIdDef to use this with the -- MkPersistSettings for our block. -- --
--   mkPersist (setImplicitIdDef uuidDef sqlSettings) [persistLowerCase| ... |]
--   
-- -- TODO: either explain interaction with mkMigrate or fix it. see issue -- #1249 for more details. data () => ImplicitIdDef data () => EntityJSON EntityJSON :: Name -> Name -> EntityJSON -- | Name of the toJSON implementation for Entity a. [entityToJSON] :: EntityJSON -> Name -- | Name of the fromJSON implementation for Entity a. [entityFromJSON] :: EntityJSON -> Name -- | Settings to be passed to the mkPersist function. data () => MkPersistSettings -- | Return type of template-reading functions. type JavascriptUrl url = url -> [(Text, Text)] -> Text -> Javascript type CssUrl url = url -> [(Text, Text)] -> Text -> Css -- | A function generating an Html given a URL-rendering function. type HtmlUrl url = Render url -> Html data () => SomeMessage master SomeMessage :: msg -> SomeMessage master -- | an RFC1766 / ISO 639-1 language code (eg, fr, en-GB, -- etc). type Lang = Text -- | the RenderMessage is used to provide translations for a message -- types -- -- The master argument exists so that it is possible to provide -- more than one set of translations for a message type. This is -- useful if a library provides a default set of translations, but the -- user of the library wants to provide a different set of translations. class () => RenderMessage master message renderMessage :: RenderMessage master message => master -> [Lang] -> message -> Text -- | ToMessage is used to convert the value inside #{ } to -- Text -- -- The primary purpose of this class is to allow the value in #{ } to be -- a String or Text rather than forcing it to always be -- Text. class () => ToMessage a toMessage :: ToMessage a => a -> Text data () => FileInfo class RenderRoute a => RouteAttrs a routeAttrs :: RouteAttrs a => Route a -> Set Text class RenderRoute a => ParseRoute a parseRoute :: ParseRoute a => ([Text], [(Text, Text)]) -> Maybe (Route a) class Eq Route a => RenderRoute a where { -- | The type-safe URLs associated with a site argument. data family Route a; } renderRoute :: RenderRoute a => Route a -> ([Text], [(Text, Text)]) -- | The type-safe URLs associated with a site argument. data family Route a -- | A handler monad for subsite data () => SubHandlerFor sub master a -- | Responses to indicate some form of an error occurred. data () => ErrorResponse -- | The requested resource was not found. Examples of when this occurs -- include when an incorrect URL is used, or yesod-persistent's -- get404 doesn't find a value. HTTP status: 404. NotFound :: ErrorResponse -- | Some sort of unexpected exception. If your application uses -- throwIO or error to throw an exception, this is the -- form it would take. HTTP status: 500. InternalError :: !Text -> ErrorResponse -- | Indicates some sort of invalid or missing argument, like a missing -- query parameter or malformed JSON body. Examples Yesod functions that -- send this include requireCheckJsonBody and -- Yesod.Auth.GoogleEmail2. HTTP status: 400. InvalidArgs :: ![Text] -> ErrorResponse -- | Indicates the user is not logged in. This is thrown when -- isAuthorized returns AuthenticationRequired. HTTP -- code: 401. NotAuthenticated :: ErrorResponse -- | Indicates the user doesn't have permission to access the requested -- resource. This is thrown when isAuthorized returns -- Unauthorized. HTTP code: 403. PermissionDenied :: !Text -> ErrorResponse -- | Indicates the URL would have been valid if used with a different HTTP -- method (e.g. a GET was used, but only POST is handled.) HTTP code: -- 405. BadMethod :: !Method -> ErrorResponse -- | Prevents a response body from being fully evaluated before sending the -- request. -- -- Since 1.1.0 newtype () => DontFullyEvaluate a DontFullyEvaluate :: a -> DontFullyEvaluate a [unDontFullyEvaluate] :: DontFullyEvaluate a -> a type ContentType = ByteString newtype () => RepXml RepXml :: Content -> RepXml newtype () => RepPlain RepPlain :: Content -> RepPlain newtype () => RepJson RepJson :: Content -> RepJson type RepHtml = Html data () => TypedContent TypedContent :: !ContentType -> !Content -> TypedContent -- | Content for a web page. By providing this datatype, we can easily -- create generic site templates, which would have the type signature: -- --
--   PageContent url -> HtmlUrl url
--   
data () => PageContent url PageContent :: !Html -> !Maybe Text -> !HtmlUrl url -> !HtmlUrl url -> PageContent url [pageTitle] :: PageContent url -> !Html [pageDescription] :: PageContent url -> !Maybe Text [pageHead] :: PageContent url -> !HtmlUrl url [pageBody] :: PageContent url -> !HtmlUrl url -- | Newtype wrapper allowing injection of arbitrary content into CSS. -- -- Usage: -- --
--   toWidget $ CssBuilder "p { color: red }"
--   
-- -- Since: 1.1.3 newtype () => CssBuilder CssBuilder :: Builder -> CssBuilder [unCssBuilder] :: CssBuilder -> Builder -- | A generic widget, allowing specification of both the subsite and -- master site datatypes. While this is simply a WriterT, we -- define a newtype for better error messages. data () => WidgetFor site a -- | A generic handler monad, which can have a different subsite and master -- site. We define a newtype for better error message. data () => HandlerFor site a -- | Like WaiSubsite, but applies parent site's middleware and -- isAuthorized. newtype () => WaiSubsiteWithAuth WaiSubsiteWithAuth :: Application -> WaiSubsiteWithAuth [runWaiSubsiteWithAuth] :: WaiSubsiteWithAuth -> Application -- | Wrap up a normal WAI application as a Yesod subsite. Ignore parent -- site's middleware and isAuthorized. newtype () => WaiSubsite WaiSubsite :: Application -> WaiSubsite [runWaiSubsite] :: WaiSubsite -> Application type Texts = [Text] type BottomOfHeadAsync master = [Text] -> Maybe HtmlUrl Route master -> HtmlUrl Route master data () => ScriptLoadPosition master BottomOfBody :: ScriptLoadPosition master BottomOfHeadBlocking :: ScriptLoadPosition master BottomOfHeadAsync :: !BottomOfHeadAsync master -> ScriptLoadPosition master data () => AuthResult Authorized :: AuthResult AuthenticationRequired :: AuthResult Unauthorized :: !Text -> AuthResult -- | How to determine the root of the application for constructing URLs. -- -- Note that future versions of Yesod may add new constructors without -- bumping the major version number. As a result, you should not -- pattern match on Approot values. data () => Approot master -- | No application root. ApprootRelative :: Approot master ApprootStatic :: !Text -> Approot master ApprootMaster :: !master -> Text -> Approot master ApprootRequest :: !master -> Request -> Text -> Approot master data () => FileUpload FileUploadMemory :: !BackEnd ByteString -> FileUpload FileUploadDisk :: !InternalState -> BackEnd FilePath -> FileUpload FileUploadSource :: !BackEnd (ConduitT () ByteString (ResourceT IO) ()) -> FileUpload -- | A tuple containing both the POST parameters and submitted files. type RequestBodyContents = ([(Text, Text)], [(Text, FileInfo)]) -- | The parsed request information. This type augments the standard WAI -- Request with additional information. data () => YesodRequest YesodRequest :: ![(Text, Text)] -> ![(Text, Text)] -> !Request -> ![Text] -> !Maybe Text -> !SessionMap -> ![ContentType] -> YesodRequest -- | Same as queryString, but decoded to Text. [reqGetParams] :: YesodRequest -> ![(Text, Text)] [reqCookies] :: YesodRequest -> ![(Text, Text)] [reqWaiRequest] :: YesodRequest -> !Request -- | Languages which the client supports. This is an ordered list by -- preference. [reqLangs] :: YesodRequest -> ![Text] -- | A random, session-specific token used to prevent CSRF attacks. [reqToken] :: YesodRequest -> !Maybe Text -- | Initial session sent from the client. -- -- Since 1.2.0 [reqSession] :: YesodRequest -> !SessionMap -- | An ordered list of the accepted content types. -- -- Since 1.2.0 [reqAccept] :: YesodRequest -> ![ContentType] newtype () => SessionBackend SessionBackend :: (Request -> IO (SessionMap, SaveSession)) -> SessionBackend -- | Return the session data and a function to save the session [sbLoadSession] :: SessionBackend -> Request -> IO (SessionMap, SaveSession) type SessionMap = Map Text ByteString -- | Any type which can be converted to TypedContent. -- -- Since 1.2.0 class ToContent a => ToTypedContent a toTypedContent :: ToTypedContent a => a -> TypedContent class ToTypedContent a => HasContentType a getContentType :: (HasContentType a, Monad m) => m a -> ContentType -- | A class for all data which can be sent in a streaming response. Note -- that for textual data, instances must use UTF-8 encoding. -- -- Since 1.2.0 class () => ToFlushBuilder a toFlushBuilder :: ToFlushBuilder a => a -> Flush Builder -- | Anything which can be converted into Content. Most of the time, -- you will want to use the ContentBuilder constructor. An easier -- approach will be to use a pre-defined toContent function, such -- as converting your data into a lazy bytestring and then calling -- toContent on that. -- -- Please note that the built-in instances for lazy data structures -- (String, lazy ByteString, lazy Text and -- Html) will not automatically include the content length for the -- ContentBuilder constructor. class () => ToContent a toContent :: ToContent a => a -> Content class MonadHandler m => MonadWidget (m :: Type -> Type) liftWidget :: MonadWidget m => WidgetFor (HandlerSite m) a -> m a class (MonadResource m, MonadLogger m) => MonadHandler (m :: Type -> Type) where { type family HandlerSite (m :: Type -> Type); type family SubHandlerSite (m :: Type -> Type); } liftHandler :: MonadHandler m => HandlerFor (HandlerSite m) a -> m a liftSubHandler :: MonadHandler m => SubHandlerFor (SubHandlerSite m) (HandlerSite m) a -> m a type family HandlerSite (m :: Type -> Type) type family SubHandlerSite (m :: Type -> Type) -- | Internal representation of a single provided representation. data () => ProvidedRep (m :: Type -> Type) -- | Add a fragment identifier to a route to be used when redirecting. For -- example: -- --
--   redirect (NewsfeedR :#: storyId)
--   
-- -- @since 1.2.9. data () => Fragment a b (:#:) :: a -> b -> Fragment a b -- | Some value which can be turned into a URL for redirects. class () => RedirectUrl master a -- | Converts the value to the URL and a list of query-string parameters. toTextUrl :: (RedirectUrl master a, MonadHandler m, HandlerSite m ~ master) => a -> m Text type HandlerT site (m :: Type -> Type) = HandlerFor site class () => ToWidgetHead site a toWidgetHead :: (ToWidgetHead site a, MonadWidget m, HandlerSite m ~ site) => a -> m () class () => ToWidgetBody site a toWidgetBody :: (ToWidgetBody site a, MonadWidget m, HandlerSite m ~ site) => a -> m () -- | Allows adding some CSS to the page with a specific media type. -- -- Since 1.2 class () => ToWidgetMedia site a -- | Add the given content to the page, but only for the given media type. -- -- Since 1.2 toWidgetMedia :: (ToWidgetMedia site a, MonadWidget m, HandlerSite m ~ site) => Text -> a -> m () class () => ToWidget site a toWidget :: (ToWidget site a, MonadWidget m, HandlerSite m ~ site) => a -> m () type WidgetT site (m :: Type -> Type) = WidgetFor site class () => YesodSubDispatch sub master yesodSubDispatch :: YesodSubDispatch sub master => YesodSubRunnerEnv sub master -> Application -- | This class is automatically instantiated when you use the template -- haskell mkYesod function. You should never need to deal with it -- directly. class Yesod site => YesodDispatch site yesodDispatch :: YesodDispatch site => YesodRunnerEnv site -> Application type LiteWidget = WidgetFor LiteApp type LiteHandler = HandlerFor LiteApp newtype () => LiteApp LiteApp :: (Method -> [Text] -> Maybe (LiteHandler TypedContent)) -> LiteApp [unLiteApp] :: LiteApp -> Method -> [Text] -> Maybe (LiteHandler TypedContent) -- | A type-safe, concise method of creating breadcrumbs for pages. For -- each resource, you declare the title of the page and the parent -- resource (if present). class () => YesodBreadcrumbs site -- | Returns the title and the parent resource, if available. If you return -- a Nothing, then this is considered a top-level page. breadcrumb :: YesodBreadcrumbs site => Route site -> HandlerFor site (Text, Maybe (Route site)) -- | General opts data type for generating yesod. -- -- Contains options for what instances are derived for the route. Use the -- setting functions on defaultOpts to set specific fields. data () => RouteOpts type Env = Map Text [Text] data () => FormMessage MsgInvalidInteger :: Text -> FormMessage MsgInvalidNumber :: Text -> FormMessage MsgInvalidEntry :: Text -> FormMessage MsgInvalidUrl :: Text -> FormMessage MsgInvalidEmail :: Text -> FormMessage MsgInvalidTimeFormat :: FormMessage MsgInvalidHour :: Text -> FormMessage MsgInvalidMinute :: Text -> FormMessage MsgInvalidSecond :: Text -> FormMessage MsgInvalidDay :: FormMessage MsgCsrfWarning :: FormMessage MsgValueRequired :: FormMessage MsgInputNotFound :: Text -> FormMessage MsgSelectNone :: FormMessage MsgInvalidBool :: Text -> FormMessage MsgBoolYes :: FormMessage MsgBoolNo :: FormMessage MsgDelete :: FormMessage MsgInvalidHexColorFormat :: Text -> FormMessage MsgInvalidDatetimeFormat :: Text -> FormMessage data () => Field (m :: Type -> Type) a Field :: ([Text] -> [FileInfo] -> m (Either (SomeMessage (HandlerSite m)) (Maybe a))) -> FieldViewFunc m a -> Enctype -> Field (m :: Type -> Type) a [fieldParse] :: Field (m :: Type -> Type) a -> [Text] -> [FileInfo] -> m (Either (SomeMessage (HandlerSite m)) (Maybe a)) [fieldView] :: Field (m :: Type -> Type) a -> FieldViewFunc m a [fieldEnctype] :: Field (m :: Type -> Type) a -> Enctype type FieldViewFunc (m :: Type -> Type) a = Text -> Text -> [(Text, Text)] -> Either Text a -> Bool -> WidgetFor HandlerSite m () data () => FieldView site FieldView :: Markup -> Maybe Markup -> Text -> WidgetFor site () -> Maybe Markup -> Bool -> FieldView site [fvLabel] :: FieldView site -> Markup [fvTooltip] :: FieldView site -> Maybe Markup [fvId] :: FieldView site -> Text [fvInput] :: FieldView site -> WidgetFor site () [fvErrors] :: FieldView site -> Maybe Markup [fvRequired] :: FieldView site -> Bool data () => FieldSettings master FieldSettings :: SomeMessage master -> Maybe (SomeMessage master) -> Maybe Text -> Maybe Text -> [(Text, Text)] -> FieldSettings master [fsLabel] :: FieldSettings master -> SomeMessage master [fsTooltip] :: FieldSettings master -> Maybe (SomeMessage master) [fsId] :: FieldSettings master -> Maybe Text [fsName] :: FieldSettings master -> Maybe Text [fsAttrs] :: FieldSettings master -> [(Text, Text)] newtype () => AForm (m :: Type -> Type) a AForm :: ((HandlerSite m, [Text]) -> Maybe (Env, FileEnv) -> Ints -> m (FormResult a, [FieldView (HandlerSite m)] -> [FieldView (HandlerSite m)], Ints, Enctype)) -> AForm (m :: Type -> Type) a [unAForm] :: AForm (m :: Type -> Type) a -> (HandlerSite m, [Text]) -> Maybe (Env, FileEnv) -> Ints -> m (FormResult a, [FieldView (HandlerSite m)] -> [FieldView (HandlerSite m)], Ints, Enctype) type MForm (m :: Type -> Type) a = RWST (Maybe (Env, FileEnv), HandlerSite m, [Lang]) Enctype Ints m a -- | MForm variant stacking a WriterT. The following code -- example using a monadic form MForm: -- --
--   formToAForm $ do
--     (field1F, field1V) <- mreq textField MsgField1 Nothing
--     (field2F, field2V) <- mreq (checkWith field1F textField) MsgField2 Nothing
--     (field3F, field3V) <- mreq (checkWith field1F textField) MsgField3 Nothing
--     return
--       ( MyForm <$> field1F <*> field2F <*> field3F
--       , [field1V, field2V, field3V]
--       )
--   
-- -- Could be rewritten as follows using WForm: -- --
--   wFormToAForm $ do
--     field1F <- wreq textField MsgField1 Nothing
--     field2F <- wreq (checkWith field1F textField) MsgField2 Nothing
--     field3F <- wreq (checkWith field1F textField) MsgField3 Nothing
--     return $ MyForm <$> field1F <*> field2F <*> field3F
--   
type WForm (m :: Type -> Type) a = MForm WriterT [FieldView HandlerSite m] m a type FileEnv = Map Text [FileInfo] data () => Ints IntCons :: Int -> Ints -> Ints IntSingle :: Int -> Ints -- | The encoding type required by a form. The ToHtml instance -- produces values that can be inserted directly into HTML. data () => Enctype UrlEncoded :: Enctype Multipart :: Enctype -- | A form can produce three different results: there was no data -- available, the data was invalid, or there was a successful parse. -- -- The Applicative instance will concatenate the failure messages -- in two FormResults. The Alternative instance will choose -- FormFailure before FormSuccess, and FormMissing -- last of all. data () => FormResult a FormMissing :: FormResult a FormFailure :: [Text] -> FormResult a FormSuccess :: a -> FormResult a -- | Type for a form which parses a value of type a with the base -- monad m (usually your Handler). Can compose this -- using its Applicative instance. newtype () => FormInput (m :: Type -> Type) a FormInput :: (HandlerSite m -> [Text] -> Env -> FileEnv -> m (Either DText a)) -> FormInput (m :: Type -> Type) a [unFormInput] :: FormInput (m :: Type -> Type) a -> HandlerSite m -> [Text] -> Env -> FileEnv -> m (Either DText a) type FormRender (m :: Type -> Type) a = AForm m a -> Markup -> MForm m (FormResult a, WidgetFor HandlerSite m ()) -- | A structure holding a list of options. Typically you can use a -- convenience function like mkOptionList or optionsPairs -- instead of creating this directly. -- -- Extended by OptionListGrouped in 1.7.0. data () => OptionList a OptionList :: [Option a] -> (Text -> Maybe a) -> OptionList a [olOptions] :: OptionList a -> [Option a] -- | A function mapping from the form's value (optionExternalValue) -- to the selected Haskell value (optionInternalValue). [olReadExternal] :: OptionList a -> Text -> Maybe a OptionListGrouped :: [(Text, [Option a])] -> (Text -> Maybe a) -> OptionList a [olOptionsGrouped] :: OptionList a -> [(Text, [Option a])] -- | A function mapping from the form's value (optionExternalValue) -- to the selected Haskell value (optionInternalValue). [olReadExternalGrouped] :: OptionList a -> Text -> Maybe a type AutoFocus = Bool -- | A newtype wrapper around a Text whose ToMarkup instance -- converts newlines to HTML <br> tags. -- -- (When text is entered into a <textarea>, newline -- characters are used to separate lines. If this text is then placed -- verbatim into HTML, the lines won't be separated, thus the need for -- replacing with <br> tags). If you don't need this -- functionality, simply use unTextarea to access the raw text. newtype () => Textarea Textarea :: Text -> Textarea [unTextarea] :: Textarea -> Text newtype () => DBRunner site DBRunner :: (forall a. () => YesodDB site a -> HandlerFor site a) -> DBRunner site [runDBRunner] :: DBRunner site -> forall a. () => YesodDB site a -> HandlerFor site a -- | Since 1.2.0 class YesodPersist site => YesodPersistRunner site -- | This function differs from runDB in that it returns a database -- runner function, as opposed to simply running a single action. This -- will usually mean that a connection is taken from a pool and then -- reused for each invocation. This can be useful for creating streaming -- responses; see runDBSource. -- -- It additionally returns a cleanup function to free the connection. If -- your code finishes successfully, you must call this cleanup to -- indicate changes should be committed. Otherwise, for SQL backends at -- least, a rollback will be used instead. -- -- Since 1.2.0 getDBRunner :: YesodPersistRunner site => HandlerFor site (DBRunner site, HandlerFor site ()) class Monad YesodDB site => YesodPersist site where { type family YesodPersistBackend site; } -- | Allows you to execute database actions within Yesod Handlers. For -- databases that support it, code inside the action will run as an -- atomic transaction. -- --

Example Usage

-- --
--   userId <- runDB $ do
--     userId <- insert $ User "username" "email@example.com"
--     insert_ $ UserPreferences userId True
--     pure userId
--   
runDB :: YesodPersist site => YesodDB site a -> HandlerFor site a type family YesodPersistBackend site type YesodDB site = ReaderT YesodPersistBackend site HandlerFor site -- | Each feed entry data () => FeedEntry url FeedEntry :: url -> UTCTime -> Text -> Html -> Maybe (EntryEnclosure url) -> [EntryCategory] -> FeedEntry url [feedEntryLink] :: FeedEntry url -> url [feedEntryUpdated] :: FeedEntry url -> UTCTime [feedEntryTitle] :: FeedEntry url -> Text [feedEntryContent] :: FeedEntry url -> Html -- | Allows enclosed data: RSS <enclosure> or Atom <link -- rel=enclosure> [feedEntryEnclosure] :: FeedEntry url -> Maybe (EntryEnclosure url) -- | Allows categories data: RSS <category> or Atom <link -- term=category> [feedEntryCategories] :: FeedEntry url -> [EntryCategory] -- | RSS 2.0 and Atom allow category in a feed entry. -- -- -- -- RSS feeds ignore categoryLabel data () => EntryCategory EntryCategory :: Maybe Text -> Maybe Text -> Text -> EntryCategory -- | category identifier [categoryDomain] :: EntryCategory -> Maybe Text -- | Human-readable label Atom only [categoryLabel] :: EntryCategory -> Maybe Text -- | identified categorization scheme via URI [categoryValue] :: EntryCategory -> Text -- | RSS and Atom allow for linked content to be enclosed in a feed entry. -- This represents the enclosed content. -- -- Atom feeds ignore enclosedSize and enclosedMimeType. data () => EntryEnclosure url EntryEnclosure :: url -> Int -> Text -> EntryEnclosure url [enclosedUrl] :: EntryEnclosure url -> url -- | Specified in bytes [enclosedSize] :: EntryEnclosure url -> Int [enclosedMimeType] :: EntryEnclosure url -> Text -- | The overall feed data () => Feed url Feed :: Text -> url -> url -> Text -> Html -> Text -> UTCTime -> Maybe (url, Text) -> [FeedEntry url] -> Feed url [feedTitle] :: Feed url -> Text [feedLinkSelf] :: Feed url -> url [feedLinkHome] :: Feed url -> url [feedAuthor] :: Feed url -> Text -- | note: currently only used for Rss [feedDescription] :: Feed url -> Html -- | note: currently only used for Rss, possible values: -- http://www.rssboard.org/rss-language-codes [feedLanguage] :: Feed url -> Text [feedUpdated] :: Feed url -> UTCTime [feedLogo] :: Feed url -> Maybe (url, Text) [feedEntries] :: Feed url -> [FeedEntry url] -- | Data type for holding all settings for combining files. -- -- This data type is a settings type. For more information, see: -- -- http://www.yesodweb.com/book/settings-types -- -- Since 1.2.0 data () => CombineSettings type StaticRoute = Route Static -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the Maybe monad. -- -- Computations are actions that may produce a value or exit. -- -- The return function yields a computation that produces that -- value, while >>= sequences two subcomputations, exiting -- if either computation does. newtype () => MaybeT (m :: Type -> Type) a MaybeT :: m (Maybe a) -> MaybeT (m :: Type -> Type) a [runMaybeT] :: MaybeT (m :: Type -> Type) a -> m (Maybe a) data () => Auth class () => RawJS a rawJS :: RawJS a => a -> RawJavascript newtype () => RawJavascript RawJavascript :: Builder -> RawJavascript -- | A typeclass for types that can be interpolated in CoffeeScript -- templates. class () => ToJavascript a toJavascript :: ToJavascript a => a -> Javascript -- | Newtype wrapper of Builder. newtype () => Javascript Javascript :: Builder -> Javascript [unJavascript] :: Javascript -> Builder -- | Defines how we want to use the environment variables when loading a -- config file. Use the smart constructors provided by this module. data () => EnvUsage newtype () => MergedValue MergedValue :: Value -> MergedValue [getMergedValue] :: MergedValue -> Value data () => AuthException InvalidFacebookResponse :: AuthException -- | Class which states that the given site is an instance of -- YesodAuth and that its AuthId is a lookup key for -- the full user information in a YesodPersist database. -- -- The default implementation of getAuthEntity assumes that the -- AuthId for the YesodAuth superclass is in fact a -- persistent Key for the given value. This is the common case -- in Yesod, and means that you can easily look up the full information -- on a given user. class (YesodAuth master, YesodPersist master) => YesodAuthPersist master where { -- | If the AuthId for a given site is a persistent ID, this will -- give the value for that entity. E.g.: -- --
    --   type AuthId MySite = UserId
    --   AuthEntity MySite ~ User
    --   
type family AuthEntity master; type AuthEntity master = KeyEntity AuthId master; } getAuthEntity :: (YesodAuthPersist master, MonadHandler m, HandlerSite m ~ master) => AuthId master -> m (Maybe (AuthEntity master)) -- | If the AuthId for a given site is a persistent ID, this will -- give the value for that entity. E.g.: -- --
--   type AuthId MySite = UserId
--   AuthEntity MySite ~ User
--   
type family AuthEntity master class (Yesod master, PathPiece AuthId master, RenderMessage master FormMessage) => YesodAuth master where { type family AuthId master; } -- | specify the layout. Uses defaultLayout by default authLayout :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master) => WidgetFor master () -> m Html -- | Default destination on successful login, if no other destination -- exists. loginDest :: YesodAuth master => master -> Route master -- | Default destination on successful logout, if no other destination -- exists. logoutDest :: YesodAuth master => master -> Route master -- | Perform authentication based on the given credentials. -- -- Default implementation is in terms of getAuthId -- -- @since: 1.4.4 authenticate :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master) => Creds master -> m (AuthenticationResult master) -- | Determine the ID associated with the set of credentials. -- -- Default implementation is in terms of authenticate getAuthId :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master) => Creds master -> m (Maybe (AuthId master)) -- | Which authentication backends to use. authPlugins :: YesodAuth master => master -> [AuthPlugin master] -- | What to show on the login page. -- -- By default this calls defaultLoginHandler, which concatenates -- plugin widgets and wraps the result in authLayout. Override if -- you need fancy widget containers, additional functionality, or an -- entirely custom page. For example, in some applications you may want -- to prevent the login page being displayed for a user who is already -- logged in, even if the URL is visited explicitly; this can be done by -- overriding loginHandler in your instance declaration with -- something like: -- --
--   instance YesodAuth App where
--       ...
--       loginHandler = do
--           ma <- lift maybeAuthId
--           when (isJust ma) $
--               lift $ redirect HomeR   -- or any other Handler code you want
--           defaultLoginHandler
--   
loginHandler :: YesodAuth master => AuthHandler master Html -- | Used for i18n of messages provided by this package. renderAuthMessage :: YesodAuth master => master -> [Text] -> AuthMessage -> Text -- | After login and logout, redirect to the referring page, instead of -- loginDest and logoutDest. Default is False. redirectToReferer :: YesodAuth master => master -> Bool -- | When being redirected to the login page should the current page be set -- to redirect back to. Default is True. redirectToCurrent :: YesodAuth master => master -> Bool -- | Return an HTTP connection manager that is stored in the foundation -- type. This allows backends to reuse persistent connections. If none of -- the backends you're using use HTTP connections, you can safely return -- error "authHttpManager" here. authHttpManager :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master) => m Manager -- | Called on a successful login. By default, calls addMessageI -- "success" NowLoggedIn. onLogin :: (YesodAuth master, MonadHandler m, master ~ HandlerSite m) => m () -- | Called on logout. By default, does nothing onLogout :: (YesodAuth master, MonadHandler m, master ~ HandlerSite m) => m () -- | Retrieves user credentials, if user is authenticated. -- -- By default, this calls defaultMaybeAuthId to get the user ID -- from the session. This can be overridden to allow authentication via -- other means, such as checking for a special token in a request header. -- This is especially useful for creating an API to be accessed via some -- means other than a browser. maybeAuthId :: (YesodAuth master, MonadHandler m, master ~ HandlerSite m) => m (Maybe (AuthId master)) -- | Called on login error for HTTP requests. By default, calls -- addMessage with "error" as status and redirects to -- dest. onErrorHtml :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master) => Route master -> Text -> m Html -- | runHttpRequest gives you a chance to handle an HttpException and retry -- The default behavior is to simply execute the request which will throw -- an exception on failure -- -- The HTTP Request is given in case it is useful to change -- behavior based on inspecting the request. This is an experimental API -- that is not broadly used throughout the yesod-auth code base runHttpRequest :: (YesodAuth master, MonadHandler m, HandlerSite m ~ master, MonadUnliftIO m) => Request -> (Response BodyReader -> m a) -> m a type family AuthId master -- | User credentials data () => Creds master Creds :: Text -> Text -> [(Text, Text)] -> Creds master -- | How the user was authenticated [credsPlugin] :: Creds master -> Text -- | Identifier. Exact meaning depends on plugin. [credsIdent] :: Creds master -> Text [credsExtra] :: Creds master -> [(Text, Text)] data () => AuthPlugin master AuthPlugin :: Text -> (Method -> [Piece] -> AuthHandler master TypedContent) -> ((Route Auth -> Route master) -> WidgetFor master ()) -> AuthPlugin master [apName] :: AuthPlugin master -> Text [apDispatch] :: AuthPlugin master -> Method -> [Piece] -> AuthHandler master TypedContent [apLogin] :: AuthPlugin master -> (Route Auth -> Route master) -> WidgetFor master () -- | The result of an authentication based on credentials data () => AuthenticationResult master -- | Authenticated successfully Authenticated :: AuthId master -> AuthenticationResult master -- | Invalid credentials provided by user UserError :: AuthMessage -> AuthenticationResult master -- | Some other error ServerError :: Text -> AuthenticationResult master type AuthHandler master a = forall (m :: Type -> Type). MonadAuthHandler master m => m a type MonadAuthHandler master (m :: Type -> Type) = (MonadHandler m, YesodAuth master, master ~ HandlerSite m, Auth ~ SubHandlerSite m, MonadUnliftIO m) type AuthRoute = Route Auth data User User :: !Text -> !BCrypt -> !Maybe HashedApiKey -> !Bool -> !Bool -> !Bool -> User [userName] :: User -> !Text [userPasswordHash] :: User -> !BCrypt [userApiToken] :: User -> !Maybe HashedApiKey [userPrivateDefault] :: User -> !Bool [userArchiveDefault] :: User -> !Bool [userPrivacyLock] :: User -> !Bool newtype BCrypt BCrypt :: Text -> BCrypt [unBCrypt] :: BCrypt -> Text newtype UserNameP UserNameP :: Text -> UserNameP [unUserNameP] :: UserNameP -> Text type DBM m a = MonadUnliftIO m => SqlPersistT m a class HasConstructor (f :: Type -> Type) genericConstrName :: HasConstructor f => f x -> String newtype BmSlug BmSlug :: Text -> BmSlug [unBmSlug] :: BmSlug -> Text newtype NtSlug NtSlug :: Text -> NtSlug [unNtSlug] :: NtSlug -> Text newtype ApiKey ApiKey :: Text -> ApiKey [unApiKey] :: ApiKey -> Text newtype HashedApiKey HashedApiKey :: Text -> HashedApiKey -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config -- files, theoretically even a database. data AppSettings AppSettings :: String -> SqliteConf -> Maybe Text -> HostPreference -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Text -> Maybe Text -> Bool -> Maybe Text -> Maybe Int -> Maybe Text -> Bool -> Bool -> AppSettings -- | Directory from which to serve static files. [appStaticDir] :: AppSettings -> String -- | Configuration settings for accessing the database. [appDatabaseConf] :: AppSettings -> SqliteConf -- | Base for all generated URLs. If Nothing, determined from the -- request headers. [appRoot] :: AppSettings -> Maybe Text -- | Host/interface the server should bind to. [appHost] :: AppSettings -> HostPreference -- | Port to listen on [appPort] :: AppSettings -> Int -- | Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. [appIpFromHeader] :: AppSettings -> Bool -- | Use detailed request logging system [appDetailedRequestLogging] :: AppSettings -> Bool -- | Should all log messages be displayed? [appShouldLogAll] :: AppSettings -> Bool -- | Use the reload version of templates [appReloadTemplates] :: AppSettings -> Bool -- | Assume that files in the static dir may change after compilation [appMutableStatic] :: AppSettings -> Bool -- | Perform no stylesheet/script combining [appSkipCombining] :: AppSettings -> Bool -- | Copyright text to appear in the footer of the page [appCopyright] :: AppSettings -> Text -- | Google Analytics code [appAnalytics] :: AppSettings -> Maybe Text -- | Indicate if auth dummy login should be enabled. [appAuthDummyLogin] :: AppSettings -> Bool -- | Socks proxy host to use when making archive requests [appArchiveSocksProxyHost] :: AppSettings -> Maybe Text -- | Socks proxy port to use when making archive requests [appArchiveSocksProxyPort] :: AppSettings -> Maybe Int -- | Uri to app source code [appSourceCodeUri] :: AppSettings -> Maybe Text [appSSLOnly] :: AppSettings -> Bool [appAllowNonHttpUrlSchemes] :: AppSettings -> Bool type DB a = forall m. DBM m a type DBVal val = (PersistEntity val, PersistEntityBackend val ~ SqlBackend, PersistStore (PersistEntityBackend val)) newtype UTCTimeStr UTCTimeStr :: UTCTime -> UTCTimeStr [unUTCTimeStr] :: UTCTimeStr -> UTCTime newtype TagsP TagsP :: [Text] -> TagsP [unTagsP] :: TagsP -> [Text] data SharedP SharedAll :: SharedP SharedPublic :: SharedP SharedPrivate :: SharedP data FilterP FilterAll :: FilterP FilterUnread :: FilterP FilterUntagged :: FilterP FilterStarred :: FilterP FilterSingle :: BmSlug -> FilterP newtype UnreadOnly UnreadOnly :: Bool -> UnreadOnly [unUnreadOnly] :: UnreadOnly -> Bool type Page = Int64 data Bookmark Bookmark :: !UserId -> !BmSlug -> !Text -> !Text -> !Text -> !UTCTime -> !Bool -> !Bool -> !Bool -> !Maybe Text -> Bookmark [bookmarkUserId] :: Bookmark -> !UserId [bookmarkSlug] :: Bookmark -> !BmSlug [bookmarkHref] :: Bookmark -> !Text [bookmarkDescription] :: Bookmark -> !Text [bookmarkExtended] :: Bookmark -> !Text [bookmarkTime] :: Bookmark -> !UTCTime [bookmarkShared] :: Bookmark -> !Bool [bookmarkToRead] :: Bookmark -> !Bool [bookmarkSelected] :: Bookmark -> !Bool [bookmarkArchiveHref] :: Bookmark -> !Maybe Text data BookmarkTag BookmarkTag :: !UserId -> !Text -> !BookmarkId -> !Int -> BookmarkTag [bookmarkTagUserId] :: BookmarkTag -> !UserId [bookmarkTagTag] :: BookmarkTag -> !Text [bookmarkTagBookmarkId] :: BookmarkTag -> !BookmarkId [bookmarkTagSeq] :: BookmarkTag -> !Int type BookmarkId = Key Bookmark data Note Note :: !UserId -> !NtSlug -> !Int -> !Text -> !Text -> !Bool -> !Bool -> !UTCTime -> !UTCTime -> Note [noteUserId] :: Note -> !UserId [noteSlug] :: Note -> !NtSlug [noteLength] :: Note -> !Int [noteTitle] :: Note -> !Text [noteText] :: Note -> !Text [noteIsMarkdown] :: Note -> !Bool [noteShared] :: Note -> !Bool [noteCreated] :: Note -> !UTCTime [noteUpdated] :: Note -> !UTCTime type UserId = Key User data FileBookmark FileBookmark :: !Text -> !Text -> !Text -> !UTCTime -> !Bool -> !Bool -> !Maybe Bool -> !Maybe Text -> !Text -> FileBookmark [fileBookmarkHref] :: FileBookmark -> !Text [fileBookmarkDescription] :: FileBookmark -> !Text [fileBookmarkExtended] :: FileBookmark -> !Text [fileBookmarkTime] :: FileBookmark -> !UTCTime [fileBookmarkShared] :: FileBookmark -> !Bool [fileBookmarkToRead] :: FileBookmark -> !Bool [fileBookmarkSelected] :: FileBookmark -> !Maybe Bool [fileBookmarkArchiveHref] :: FileBookmark -> !Maybe Text [fileBookmarkTags] :: FileBookmark -> !Text data FFBookmarkNode FFBookmarkNode :: Maybe [FFBookmarkNode] -> !POSIXTime -> !Text -> !Maybe Text -> !Int -> !Int -> !POSIXTime -> !Maybe Text -> !Text -> !Text -> !Int -> !Maybe Text -> FFBookmarkNode [firefoxBookmarkChildren] :: FFBookmarkNode -> Maybe [FFBookmarkNode] [firefoxBookmarkDateAdded] :: FFBookmarkNode -> !POSIXTime [firefoxBookmarkGuid] :: FFBookmarkNode -> !Text [firefoxBookmarkIconUri] :: FFBookmarkNode -> !Maybe Text [firefoxBookmarkId] :: FFBookmarkNode -> !Int [firefoxBookmarkIndex] :: FFBookmarkNode -> !Int [firefoxBookmarkLastModified] :: FFBookmarkNode -> !POSIXTime [firefoxBookmarkRoot] :: FFBookmarkNode -> !Maybe Text [firefoxBookmarkTitle] :: FFBookmarkNode -> !Text [firefoxBookmarkType] :: FFBookmarkNode -> !Text [firefoxBookmarkTypeCode] :: FFBookmarkNode -> !Int [firefoxBookmarkUri] :: FFBookmarkNode -> !Maybe Text data TagCloudMode TagCloudModeTop :: Bool -> Int -> TagCloudMode TagCloudModeLowerBound :: Bool -> Int -> TagCloudMode TagCloudModeRelated :: Bool -> [Tag] -> TagCloudMode TagCloudModeNone :: TagCloudMode data FileNote FileNote :: !Text -> !Text -> !Text -> !Int -> !UTCTime -> !UTCTime -> FileNote [fileNoteId] :: FileNote -> !Text [fileNoteTitle] :: FileNote -> !Text [fileNoteText] :: FileNote -> !Text [fileNoteLength] :: FileNote -> !Int [fileNoteCreatedAt] :: FileNote -> !UTCTime [fileNoteUpdatedAt] :: FileNote -> !UTCTime data AccountSettingsForm AccountSettingsForm :: Bool -> Bool -> Bool -> AccountSettingsForm [_privateDefault] :: AccountSettingsForm -> Bool [_archiveDefault] :: AccountSettingsForm -> Bool [_privacyLock] :: AccountSettingsForm -> Bool data BookmarkForm BookmarkForm :: Text -> Maybe Text -> Maybe Textarea -> Maybe Text -> Maybe Bool -> Maybe Bool -> Maybe Int64 -> Maybe BmSlug -> Maybe Bool -> Maybe UTCTimeStr -> Maybe Text -> BookmarkForm [_url] :: BookmarkForm -> Text [_title] :: BookmarkForm -> Maybe Text [_description] :: BookmarkForm -> Maybe Textarea [_tags] :: BookmarkForm -> Maybe Text [_private] :: BookmarkForm -> Maybe Bool [_toread] :: BookmarkForm -> Maybe Bool [_bid] :: BookmarkForm -> Maybe Int64 [_slug] :: BookmarkForm -> Maybe BmSlug [_selected] :: BookmarkForm -> Maybe Bool [_time] :: BookmarkForm -> Maybe UTCTimeStr [_archiveUrl] :: BookmarkForm -> Maybe Text data UpsertResult a Created :: a -> UpsertResult a Updated :: a -> UpsertResult a Failed :: String -> UpsertResult a type BookmarkTagId = Key BookmarkTag type NoteId = Key Note pattern AddCookie :: () => !SetCookie -> Header -- | name and path pattern DeleteCookie :: () => !ByteString -> !ByteString -> Header -- | Convert a list of values to an Array. array :: ToJSON a => [a] -> Value -- | Unlifted async. async :: MonadUnliftIO m => m a -> m (Async a) -- | deepseq: fully evaluates the first argument, before returning -- the second. -- -- The name deepseq is used to illustrate the relationship to -- seq: where seq is shallow in the sense that it only -- evaluates the top level of its argument, deepseq traverses the -- entire data structure evaluating it completely. -- -- deepseq can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also -- useful in conjunction with parallel Strategies (see the -- parallel package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in any -- order or in parallel. To impose an actual order on evaluation, use -- pseq from Control.Parallel in the parallel -- package. deepseq :: NFData a => a -> b -> b infixr 0 `deepseq` -- | Send a Text to standard output, appending a newline, and -- chunking the data. By default, the chunk size is 2048 characters, so -- any messages below that size will be sent as one contiguous unit. If -- larger messages are used, it is possible for interleaving with other -- threads to occur. say :: MonadIO m => Text -> m () -- | void value discards or ignores the result of -- evaluation, such as the return value of an IO action. -- --

Examples

-- -- Replace the contents of a Maybe Int with unit: -- --
--   >>> void Nothing
--   Nothing
--   
--   >>> void (Just 3)
--   Just ()
--   
-- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int (): -- --
--   >>> void (Left 8675309)
--   Left 8675309
--   
--   >>> void (Right 8675309)
--   Right ()
--   
-- -- Replace every element of a list with unit: -- --
--   >>> void [1,2,3]
--   [(),(),()]
--   
-- -- Replace the second element of a pair with unit: -- --
--   >>> void (1,2)
--   (1,())
--   
-- -- Discard the result of an IO action: -- --
--   >>> mapM print [1,2]
--   1
--   2
--   [(),()]
--   
--   >>> void $ mapM print [1,2]
--   1
--   2
--   
void :: Functor f => f a -> f () -- | A convenience method to run an application using the Warp webserver on -- the specified port. Automatically calls toWaiApp. Provides a -- default set of middlewares. This set may change at any point without a -- breaking version number. Currently, it includes: -- -- -- -- If you need more fine-grained control of middlewares, please use -- toWaiApp directly. -- -- Since 1.2.0 warp :: YesodDispatch site => Int -> site -> IO () -- | If the first argument evaluates to True, then the result is the -- second argument. Otherwise an AssertionFailed exception is -- raised, containing a String with the source file and line -- number of the call to assert. -- -- Assertions can normally be turned on or off with a compiler flag (for -- GHC, assertions are normally on unless optimisation is turned on with -- -O or the -fignore-asserts option is given). When -- assertions are turned off, the first argument to assert is -- ignored, and the second argument is returned as the result. assert :: Bool -> a -> a -- | Application operator. This operator is redundant, since ordinary -- application (f x) means the same as (f $ x). -- However, $ has low, right-associative binding precedence, so it -- sometimes allows parentheses to be omitted; for example: -- --
--   f $ g $ h x  =  f (g (h x))
--   
-- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is representation-polymorphic in its -- result type, so that foo $ True where foo :: Bool -- -> Int# is well-typed. ($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $ -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
--   f x | x < 0     = ...
--       | otherwise = ...
--   
otherwise :: Bool (++) :: Monoid m => m -> m -> m infixr 5 ++ -- | Synonym for ofoldr foldr :: MonoFoldable mono => (Element mono -> b -> b) -> b -> mono -> b map :: Functor f => (a -> b) -> f a -> f b -- | The join function is the conventional monad join operator. It -- is used to remove one level of monadic structure, projecting its bound -- argument into the outer level. -- -- 'join bss' can be understood as the do -- expression -- --
--   do bs <- bss
--      bs
--   
-- --

Examples

-- -- A common use of join is to run an IO computation -- returned from an STM transaction, since STM transactions -- can't perform IO directly. Recall that -- --
--   atomically :: STM a -> IO a
--   
-- -- is used to run STM transactions atomically. So, by specializing -- the types of atomically and join to -- --
--   atomically :: STM (IO b) -> IO (IO b)
--   join       :: IO (IO b)  -> IO b
--   
-- -- we can compose them as -- --
--   join . atomically :: STM (IO b) -> IO b
--   
-- -- to run an STM transaction and the IO action it returns. join :: Monad m => m (m a) -> m a -- | Sort a ordered sequence. -- --
--   > sort [4,3,1,2]
--   [1,2,3,4]
--   
sort :: (SemiSequence seq, Ord (Element seq)) => seq -> seq -- | Synonym for otoList toList :: MonoFoldable mono => mono -> [Element mono] -- | Lifted version of evaluate. evaluate :: MonadIO m => a -> m a -- | Perform thing, guaranteeing that after will run -- after, even if an exception occurs. -- -- Same interruptible vs uninterrupible points apply as with -- bracket. See base's finally for more -- information. finally :: MonadUnliftIO m => m a -> m b -> m a -- | Flipped version of catch. handle :: (MonadUnliftIO m, Exception e) => (e -> m a) -> m a -> m a -- | General coercion to Fractional types. -- -- WARNING: This function goes through the Rational type, which -- does not have values for NaN for example. This means it does -- not round-trip. -- -- For Double it also behaves differently with or without -O0: -- --
--   Prelude> realToFrac nan -- With -O0
--   -Infinity
--   Prelude> realToFrac nan
--   NaN
--   
realToFrac :: (Real a, Fractional b) => a -> b -- | General coercion from Integral types. -- -- WARNING: This function performs silent truncation if the result type -- is not at least as big as the argument's type. fromIntegral :: (Integral a, Num b) => a -> b -- | A synonym for =$= for backwards compatibility. -- -- Since 0.4.0 ($=) :: forall (m :: Type -> Type) a b c r. Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r infixl 1 $= -- | Lift a callCC operation to the new monad. liftCallCC :: CallCC m (Maybe a) (Maybe b) -> CallCC (MaybeT m) a b -- | Case analysis for the Either type. If the value is -- Left a, apply the first function to a; if it -- is Right b, apply the second function to b. -- --

Examples

-- -- We create two values of type Either String -- Int, one using the Left constructor and another -- using the Right constructor. Then we apply "either" the -- length function (if we have a String) or the "times-two" -- function (if we have an Int): -- --
--   >>> let s = Left "foo" :: Either String Int
--   
--   >>> let n = Right 3 :: Either String Int
--   
--   >>> either length (*2) s
--   3
--   
--   >>> either length (*2) n
--   6
--   
either :: (a -> c) -> (b -> c) -> Either a b -> c -- | the identity morphism id :: forall (a :: k). Category cat => cat a a -- | morphism composition (.) :: forall (b :: k) (c :: k) (a :: k). Category cat => cat b c -> cat a b -> cat a c infixr 9 . -- | Extract the first component of a pair. fst :: (a, b) -> a -- | Extract the second component of a pair. snd :: (a, b) -> b -- | Promote a function to a monad. liftM :: Monad m => (a1 -> r) -> m a1 -> m r -- | Synonym for onull null :: MonoFoldable mono => mono -> Bool -- | Create a sequence from a single element. -- --
--   > singleton a :: String
--   "a"
--   > singleton a :: Vector Char
--   fromList "a"
--   
singleton :: MonoPointed seq => Element seq -> seq -- | Synonym for ofoldl' foldl' :: MonoFoldable mono => (a -> Element mono -> a) -> a -> mono -> a -- | The mapMaybe function is a version of map which can -- throw out elements. In particular, the functional argument returns -- something of type Maybe b. If this is Nothing, -- no element is added on to the result list. If it is Just -- b, then b is included in the result list. -- --

Examples

-- -- Using mapMaybe f x is a shortcut for -- catMaybes $ map f x in most cases: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> let readMaybeInt = readMaybe :: String -> Maybe Int
--   
--   >>> mapMaybe readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
--   >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
--   [1,3]
--   
-- -- If we map the Just constructor, the entire list should be -- returned: -- --
--   >>> mapMaybe Just [1,2,3]
--   [1,2,3]
--   
mapMaybe :: (a -> Maybe b) -> [a] -> [b] -- | Create a Value from a list of name/value Pairs. If -- duplicate keys arise, later keys and their associated values win. object :: [Pair] -> Value -- | Case analysis for the Bool type. bool x y p -- evaluates to x when p is False, and evaluates -- to y when p is True. -- -- This is equivalent to if p then y else x; that is, one can -- think of it as an if-then-else construct with its arguments reordered. -- --

Examples

-- -- Basic usage: -- --
--   >>> bool "foo" "bar" True
--   "bar"
--   
--   >>> bool "foo" "bar" False
--   "foo"
--   
-- -- Confirm that bool x y p and if p then y else -- x are equivalent: -- --
--   >>> let p = True; x = "bar"; y = "foo"
--   
--   >>> bool x y p == if p then y else x
--   True
--   
--   >>> let p = False
--   
--   >>> bool x y p == if p then y else x
--   True
--   
bool :: a -> a -> Bool -> a -- | Retrieve the value associated with the given key of an Object. -- The result is empty if the key is not present or the value -- cannot be converted to the desired type. -- -- This accessor is appropriate if the key and value must be -- present in an object for it to be valid. If the key and value are -- optional, use .:? instead. (.:) :: FromJSON a => Object -> Key -> Parser a (.=) :: (KeyValue e kv, ToJSON v) => Key -> v -> kv infixr 8 .= -- | Conditional execution of Applicative expressions. For example, -- --
--   when debug (putStrLn "Debugging")
--   
-- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | Promote a function to a monad, scanning the monadic arguments from -- left to right. For example, -- --
--   liftM2 (+) [0,1] [0,2] = [0,2,1,3]
--   liftM2 (+) (Just 1) Nothing = Nothing
--   
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r -- | The fromMaybe function takes a default value and a Maybe -- value. If the Maybe is Nothing, it returns the default -- value; otherwise, it returns the value contained in the Maybe. -- --

Examples

-- -- Basic usage: -- --
--   >>> fromMaybe "" (Just "Hello, World!")
--   "Hello, World!"
--   
-- --
--   >>> fromMaybe "" Nothing
--   ""
--   
-- -- Read an integer from a string using readMaybe. If we fail to -- parse an integer, we want to return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> fromMaybe 0 (readMaybe "5")
--   5
--   
--   >>> fromMaybe 0 (readMaybe "")
--   0
--   
fromMaybe :: a -> Maybe a -> a -- | Takes all of the Just values from a sequence of Maybe -- ts and concatenates them into an unboxed sequence of ts. -- -- Since 0.6.2 catMaybes :: (IsSequence (f (Maybe t)), Functor f, Element (f (Maybe t)) ~ Maybe t) => f (Maybe t) -> f t -- | Flipped version of <$. -- --

Examples

-- -- Replace the contents of a Maybe Int with a -- constant String: -- --
--   >>> Nothing $> "foo"
--   Nothing
--   
--   >>> Just 90210 $> "foo"
--   Just "foo"
--   
-- -- Replace the contents of an Either Int -- Int with a constant String, resulting in an -- Either Int String: -- --
--   >>> Left 8675309 $> "foo"
--   Left 8675309
--   
--   >>> Right 8675309 $> "foo"
--   Right "foo"
--   
-- -- Replace each element of a list with a constant String: -- --
--   >>> [1,2,3] $> "foo"
--   ["foo","foo","foo"]
--   
-- -- Replace the second element of a pair with a constant String: -- --
--   >>> (1,2) $> "foo"
--   (1,"foo")
--   
($>) :: Functor f => f a -> b -> f b infixl 4 $> -- | The reverse of when. unless :: Applicative f => Bool -> f () -> f () -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
--    ($)  ::              (a -> b) ->   a ->   b
--   (<$>) :: Functor f => (a -> b) -> f a -> f b
--   
-- -- Whereas $ is function application, <$> is function -- application lifted over a Functor. -- --

Examples

-- -- Convert from a Maybe Int to a Maybe -- String using show: -- --
--   >>> show <$> Nothing
--   Nothing
--   
--   >>> show <$> Just 3
--   Just "3"
--   
-- -- Convert from an Either Int Int to an -- Either Int String using show: -- --
--   >>> show <$> Left 17
--   Left 17
--   
--   >>> show <$> Right 17
--   Right "17"
--   
-- -- Double each element of a list: -- --
--   >>> (*2) <$> [1,2,3]
--   [2,4,6]
--   
-- -- Apply even to the second element of a pair: -- --
--   >>> even <$> (2,2)
--   (2,True)
--   
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | The value of seq a b is bottom if a is -- bottom, and otherwise equal to b. In other words, it -- evaluates the first argument a to weak head normal form -- (WHNF). seq is usually introduced to improve performance by -- avoiding unneeded laziness. -- -- A note on evaluation order: the expression seq a b -- does not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq returns -- a value. In particular, this means that b may be evaluated -- before a. If you need to guarantee a specific order of -- evaluation, you must use the function pseq from the -- "parallel" package. seq :: forall {r :: RuntimeRep} a (b :: TYPE r). a -> b -> b infixr 0 `seq` -- | Conditional failure of Alternative computations. Defined by -- --
--   guard True  = pure ()
--   guard False = empty
--   
-- --

Examples

-- -- Common uses of guard include conditionally signaling an error -- in an error monad and conditionally rejecting the current choice in an -- Alternative-based parser. -- -- As an example of signaling an error in the error monad Maybe, -- consider a safe division function safeDiv x y that returns -- Nothing when the denominator y is zero and -- Just (x `div` y) otherwise. For example: -- --
--   >>> safeDiv 4 0
--   Nothing
--   
-- --
--   >>> safeDiv 4 2
--   Just 2
--   
-- -- A definition of safeDiv using guards, but not guard: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y | y /= 0    = Just (x `div` y)
--               | otherwise = Nothing
--   
-- -- A definition of safeDiv using guard and Monad -- do-notation: -- --
--   safeDiv :: Int -> Int -> Maybe Int
--   safeDiv x y = do
--     guard (y /= 0)
--     return (x `div` y)
--   
guard :: Alternative f => Bool -> f () -- | Same as bracket, but does not pass the acquired resource to -- cleanup and use functions. -- -- For more information, see base's bracket_. bracket_ :: MonadUnliftIO m => m a -> m b -> m c -> m c -- | Lifted version of hIsTerminalDevice hIsTerminalDevice :: MonadIO m => Handle -> m Bool -- | Set the page title. -- -- Calling setTitle or setTitleI multiple times -- overrides previously set values. -- -- SEO Notes: -- -- setTitle :: MonadWidget m => Html -> m () stdout :: Handle stdin :: Handle -- | A variant of <*> with the arguments reversed. (<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 <**> -- | Run the given action and catch any synchronous exceptions as a -- Left value. -- -- This is parameterized on the exception type. To catch all synchronous -- exceptions, use tryAny. try :: (MonadUnliftIO m, Exception e) => m a -> m (Either e a) -- | Swap the components of a pair. swap :: (a, b) -> (b, a) -- | Unlifted asyncBound. asyncBound :: MonadUnliftIO m => m a -> m (Async a) -- | Unlifted asyncOn. asyncOn :: MonadUnliftIO m => Int -> m a -> m (Async a) -- | Unlifted asyncWithUnmask. asyncWithUnmask :: MonadUnliftIO m => ((forall b. () => m b -> m b) -> m a) -> m (Async a) -- | Unlifted asyncOnWithUnmask. asyncOnWithUnmask :: MonadUnliftIO m => Int -> ((forall b. () => m b -> m b) -> m a) -> m (Async a) -- | Unlifted withAsync. withAsync :: MonadUnliftIO m => m a -> (Async a -> m b) -> m b -- | Unlifted withAsyncBound. withAsyncBound :: MonadUnliftIO m => m a -> (Async a -> m b) -> m b -- | Unlifted withAsyncOn. withAsyncOn :: MonadUnliftIO m => Int -> m a -> (Async a -> m b) -> m b -- | Unlifted withAsyncWithUnmask. withAsyncWithUnmask :: MonadUnliftIO m => ((forall c. () => m c -> m c) -> m a) -> (Async a -> m b) -> m b -- | Unlifted withAsyncOnWithMask. withAsyncOnWithUnmask :: MonadUnliftIO m => Int -> ((forall c. () => m c -> m c) -> m a) -> (Async a -> m b) -> m b -- | Lifted wait. wait :: MonadIO m => Async a -> m a -- | Lifted waitCatch. waitCatch :: MonadIO m => Async a -> m (Either SomeException a) -- | Lifted poll. poll :: MonadIO m => Async a -> m (Maybe (Either SomeException a)) -- | A version of wait that can be used inside an STM transaction. waitSTM :: Async a -> STM a -- | A version of waitCatch that can be used inside an STM -- transaction. waitCatchSTM :: Async a -> STM (Either SomeException a) -- | A version of poll that can be used inside an STM transaction. pollSTM :: Async a -> STM (Maybe (Either SomeException a)) -- | Lifted cancel. cancel :: MonadIO m => Async a -> m () -- | Lifted uninterruptibleCancel. uninterruptibleCancel :: MonadIO m => Async a -> m () -- | Lifted cancelWith. Additionally uses toAsyncException to -- ensure async exception safety. cancelWith :: (Exception e, MonadIO m) => Async a -> e -> m () -- | Lifted waitAnyCatch. waitAnyCatch :: MonadIO m => [Async a] -> m (Async a, Either SomeException a) -- | A version of waitAnyCatch that can be used inside an STM -- transaction. waitAnyCatchSTM :: [Async a] -> STM (Async a, Either SomeException a) -- | Lifted waitAnyCatchCancel. waitAnyCatchCancel :: MonadIO m => [Async a] -> m (Async a, Either SomeException a) -- | Lifted waitAny. waitAny :: MonadIO m => [Async a] -> m (Async a, a) -- | A version of waitAny that can be used inside an STM -- transaction. waitAnySTM :: [Async a] -> STM (Async a, a) -- | Lifted waitAnyCancel. waitAnyCancel :: MonadIO m => [Async a] -> m (Async a, a) -- | Lifted waitEitherCatch. waitEitherCatch :: MonadIO m => Async a -> Async b -> m (Either (Either SomeException a) (Either SomeException b)) -- | A version of waitEitherCatch that can be used inside an STM -- transaction. waitEitherCatchSTM :: Async a -> Async b -> STM (Either (Either SomeException a) (Either SomeException b)) -- | Lifted waitEitherCatchCancel. waitEitherCatchCancel :: MonadIO m => Async a -> Async b -> m (Either (Either SomeException a) (Either SomeException b)) -- | Lifted waitEither. waitEither :: MonadIO m => Async a -> Async b -> m (Either a b) -- | A version of waitEither that can be used inside an STM -- transaction. waitEitherSTM :: Async a -> Async b -> STM (Either a b) -- | Lifted waitEither_. waitEither_ :: MonadIO m => Async a -> Async b -> m () -- | A version of waitEither_ that can be used inside an STM -- transaction. waitEitherSTM_ :: Async a -> Async b -> STM () -- | Lifted waitEitherCancel. waitEitherCancel :: MonadIO m => Async a -> Async b -> m (Either a b) -- | Lifted waitBoth. waitBoth :: MonadIO m => Async a -> Async b -> m (a, b) -- | A version of waitBoth that can be used inside an STM -- transaction. waitBothSTM :: Async a -> Async b -> STM (a, b) -- | Lifted link. link :: MonadIO m => Async a -> m () -- | Lifted link2. link2 :: MonadIO m => Async a -> Async b -> m () -- | Unlifted race. race :: MonadUnliftIO m => m a -> m b -> m (Either a b) -- | Unlifted race_. race_ :: MonadUnliftIO m => m a -> m b -> m () -- | Unlifted concurrently. concurrently :: MonadUnliftIO m => m a -> m b -> m (a, b) -- | Unlifted concurrently_. concurrently_ :: MonadUnliftIO m => m a -> m b -> m () -- | Executes a Traversable container of items concurrently, it uses -- the Flat type internally. mapConcurrently :: (MonadUnliftIO m, Traversable t) => (a -> m b) -> t a -> m (t b) -- | Similar to mapConcurrently but with arguments flipped forConcurrently :: (MonadUnliftIO m, Traversable t) => t a -> (a -> m b) -> m (t b) -- | Executes a Traversable container of items concurrently, it uses -- the Flat type internally. This function ignores the results. mapConcurrently_ :: (MonadUnliftIO m, Foldable f) => (a -> m b) -> f a -> m () -- | Similar to mapConcurrently_ but with arguments flipped forConcurrently_ :: (MonadUnliftIO m, Foldable f) => f a -> (a -> m b) -> m () -- | Unlifted replicateConcurrently. replicateConcurrently :: MonadUnliftIO f => Int -> f a -> f [a] -- | Unlifted replicateConcurrently_. replicateConcurrently_ :: (Applicative m, MonadUnliftIO m) => Int -> m a -> m () -- | Synonym for omapM_ mapM_ :: (MonoFoldable mono, Applicative m) => (Element mono -> m ()) -> mono -> m () -- | Synonym for oforM_ forM_ :: (MonoFoldable mono, Applicative m) => mono -> (Element mono -> m ()) -> m () -- | const x y always evaluates to x, ignoring its second -- argument. -- --
--   >>> const 42 "hello"
--   42
--   
-- --
--   >>> map (const 42) [0..3]
--   [42,42,42,42]
--   
const :: a -> b -> a -- | Get the current UTCTime from the system clock. getCurrentTime :: IO UTCTime -- | Lifted atomicModifyIORef'. atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b -- | error stops execution and displays an error message. error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => [Char] -> a zipWith :: Zip f => (a -> b -> c) -> f a -> f b -> f c zip :: Zip f => f a -> f b -> f (a, b) unzip :: Zip f => f (a, b) -> (f a, f b) even :: Integral a => a -> Bool -- | Lifted version of atomically atomically :: MonadIO m => STM a -> m a -- | Allocate and clean up a resource safely. -- -- For more information on motivation and usage of this function, see -- base's bracket. This function has two differences from -- the one in base. The first, and more obvious, is that it -- works on any MonadUnliftIO instance, not just IO. -- -- The more subtle difference is that this function will use -- uninterruptible masking for its cleanup handler. This is a subtle -- distinction, but at a high level, means that resource cleanup has more -- guarantees to complete. This comes at the cost that an incorrectly -- written cleanup function cannot be interrupted. -- -- For more information, please see -- https://github.com/fpco/safe-exceptions/issues/3. bracket :: MonadUnliftIO m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Strictly read the contents of the given Handle into a -- ByteString. hGetContents :: MonadIO m => Handle -> m ByteString -- | Get the maximum element of a monomorphic container, using a supplied -- element ordering function. -- -- Safe version of maximumByEx, only works on monomorphic -- containers wrapped in a NonNull. maximumBy :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> NonNull mono -> Element mono -- | Get the minimum element of a monomorphic container, using a supplied -- element ordering function. -- -- Safe version of minimumByEx, only works on monomorphic -- containers wrapped in a NonNull. minimumBy :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> NonNull mono -> Element mono -- | uncurry converts a curried function to a function on pairs. -- --

Examples

-- --
--   >>> uncurry (+) (1,2)
--   3
--   
-- --
--   >>> uncurry ($) (show, 1)
--   "1"
--   
-- --
--   >>> map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   
uncurry :: (a -> b -> c) -> (a, b) -> c -- | Lifted version of openFile openFile :: MonadIO m => FilePath -> IOMode -> m Handle -- | Synonym for olength length :: MonoFoldable mono => mono -> Int -- | Return the first element of a monomorphic container. -- -- Safe version of headEx, only works on monomorphic containers -- wrapped in a NonNull. head :: MonoFoldable mono => NonNull mono -> Element mono -- | Equivalent to groupBy (==) group :: (IsSequence seq, Eq (Element seq)) => seq -> [seq] -- | for is traverse with its arguments flipped. For a -- version that ignores the results see for_. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | Throw an asynchronous exception to another thread. -- -- Synchronously typed exceptions will be wrapped into an -- AsyncExceptionWrapper, see -- https://github.com/fpco/safe-exceptions#determining-sync-vs-async. -- -- It's usually a better idea to use the UnliftIO.Async module, -- see https://github.com/fpco/safe-exceptions#quickstart. throwTo :: (Exception e, MonadIO m) => ThreadId -> e -> m () -- | Lifted atomicWriteIORef. atomicWriteIORef :: MonadIO m => IORef a -> a -> m () -- | Lifted atomicModifyIORef. atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b stderr :: Handle -- | Repeat an action indefinitely. -- --

Examples

-- -- A common use of forever is to process input from network -- sockets, Handles, and channels (e.g. MVar and -- Chan). -- -- For example, here is how we might implement an echo server, -- using forever both to listen for client connections on a -- network socket and to echo client input on client connection handles: -- --
--   echoServer :: Socket -> IO ()
--   echoServer socket = forever $ do
--     client <- accept socket
--     forkFinally (echo client) (\_ -> hClose client)
--     where
--       echo :: Handle -> IO ()
--       echo client = forever $
--         hGetLine client >>= hPutStrLn client
--   
-- -- Note that "forever" isn't necessarily non-terminating. If the action -- is in a MonadPlus and short-circuits after some number -- of iterations. then forever actually returns -- mzero, effectively short-circuiting its caller. forever :: Applicative f => f a -> f b -- | Lifted version of hSeek hSeek :: MonadIO m => Handle -> SeekMode -> Integer -> m () -- | Lifted version of hFlush hFlush :: MonadIO m => Handle -> m () -- | Unlifted version of mask. mask :: MonadUnliftIO m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Synchronously throw the given exception. -- -- Note that, if you provide an exception value which is of an -- asynchronous type, it will be wrapped up in -- SyncExceptionWrapper. See toSyncException. throwIO :: (MonadIO m, Exception e) => e -> m a -- | Lifted version of newTChanIO newTChanIO :: MonadIO m => m (TChan a) -- | Lifted version of newBroadcastTChanIO newBroadcastTChanIO :: MonadIO m => m (TChan a) -- | Lifted version of newTQueueIO newTQueueIO :: MonadIO m => m (TQueue a) -- | Lifted version of newTBQueueIO newTBQueueIO :: MonadIO m => Natural -> m (TBQueue a) -- | Lifted version of newTMVarIO newTMVarIO :: MonadIO m => a -> m (TMVar a) -- | Catch a synchronous (but not asynchronous) exception and recover from -- it. -- -- This is parameterized on the exception type. To catch all synchronous -- exceptions, use catchAny. catch :: (MonadUnliftIO m, Exception e) => m a -> (e -> m a) -> m a -- | Write a ByteString to a file. writeFile :: MonadIO m => FilePath -> ByteString -> m () -- | Read a line from stdin -- -- Uses system locale settings getLine :: MonadIO m => m Text -- | Write a Text followed by a newline to stdout -- -- Uses system locale settings putStrLn :: MonadIO m => Text -> m () -- | An error indicating that an IO operation failed because one of -- its arguments does not exist. isDoesNotExistError :: IOError -> Bool getArgs :: MonadIO m => m [Text] -- | Lifted version of hClose hClose :: MonadIO m => Handle -> m () -- | An error indicating that an IO operation failed because one of -- its arguments is a single-use resource, which is already being used -- (for example, opening the same file twice for writing might give this -- error). isAlreadyInUseError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- user does not have sufficient operating system privilege to perform -- that operation. isPermissionError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- device is full. isFullError :: IOError -> Bool -- | An error indicating that an IO operation failed because the end -- of file has been reached. isEOFError :: IOError -> Bool -- | An error indicating that an IO operation failed because the -- operation was not possible. Any computation which returns an IO -- result may fail with isIllegalOperation. In some cases, an -- implementation will not be able to distinguish between the possible -- error causes. In this case it should fail with -- isIllegalOperation. isIllegalOperation :: IOError -> Bool -- | Split the input between the two argument arrows and combine their -- output. Note that this is in general not a functor. -- -- The default definition may be overridden with a more efficient version -- if desired. (***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c') infixr 3 *** -- | Fanout: send the input to both argument arrows and combine their -- output. -- -- The default definition may be overridden with a more efficient version -- if desired. (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 &&& -- | Lifted version of hWaitForInput hWaitForInput :: MonadIO m => Handle -> Int -> m Bool -- | Same as sortBy . comparing. -- -- Since 0.7.0 sortOn :: (Ord o, SemiSequence seq) => (Element seq -> o) -> seq -> seq -- | Synonym for oconcat concat :: (MonoFoldable mono, Monoid (Element mono)) => mono -> Element mono print :: (Show a, MonadIO m) => a -> m () -- | We define our own trace (and also its variants) which provides -- a warning when used. So that tracing is available during development, -- but the compiler reminds you to not leave them in the code for -- production. trace :: String -> a -> a -- | raise a number to a non-negative integral power (^) :: (Num a, Integral b) => a -> b -> a infixr 8 ^ -- | Boolean "and", lazy in the second argument (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or", lazy in the second argument (||) :: Bool -> Bool -> Bool infixr 2 || -- | Boolean "not" not :: Bool -> Bool -- | We define our own undefined which is marked as deprecated. This -- makes it useful to use during development, but lets you more easily -- get notifications if you accidentally ship partial code in production. -- -- The classy prelude recommendation for when you need to really have a -- partial function in production is to use error with a very -- descriptive message so that, in case an exception is thrown, you get -- more information than Prelude.undefined. -- -- Since 0.5.5 undefined :: HasCallStack => a -- | Lift a function to actions. Equivalent to Functor's fmap but -- implemented using only Applicative's methods: liftA -- f a = pure f <*> a -- -- As such this function may be used to implement a Functor -- instance from an Applicative one. -- --

Examples

-- -- Using the Applicative instance for Lists: -- --
--   >>> liftA (+1) [1, 2]
--   [2,3]
--   
-- -- Or the Applicative instance for Maybe -- --
--   >>> liftA (+1) (Just 3)
--   Just 4
--   
liftA :: Applicative f => (a -> b) -> f a -> f b -- | Lift a ternary function to actions. liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d -- | Same as >>=, but with the arguments interchanged. (=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 =<< -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r -- | Promote a function to a monad, scanning the monadic arguments from -- left to right (cf. liftM2). liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r -- | In many situations, the liftM operations can be replaced by -- uses of ap, which promotes function application. -- --
--   return f `ap` x1 `ap` ... `ap` xn
--   
-- -- is equivalent to -- --
--   liftMn f x1 x2 ... xn
--   
ap :: Monad m => m (a -> b) -> m a -> m b -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
--   >>> flip (++) "hello" "world"
--   "worldhello"
--   
flip :: (a -> b -> c) -> b -> a -> c -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b infixr 0 $! -- | until p f yields the result of applying f -- until p holds. until :: (a -> Bool) -> (a -> a) -> a -> a -- | asTypeOf is a type-restricted version of const. It is -- usually used as an infix operator, and its typing forces its first -- argument (which is usually overloaded) to have the same type as the -- second. asTypeOf :: a -> a -> a -- | the same as flip (-). -- -- Because - is treated specially in the Haskell grammar, -- (- e) is not a section, but an application of -- prefix negation. However, (subtract -- exp) is equivalent to the disallowed section. subtract :: Num a => a -> a -> a -- | The maybe function takes a default value, a function, and a -- Maybe value. If the Maybe value is Nothing, the -- function returns the default value. Otherwise, it applies the function -- to the value inside the Just and returns the result. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybe False odd (Just 3)
--   True
--   
-- --
--   >>> maybe False odd Nothing
--   False
--   
-- -- Read an integer from a string using readMaybe. If we succeed, -- return twice the integer; that is, apply (*2) to it. If -- instead we fail to parse an integer, return 0 by default: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> maybe 0 (*2) (readMaybe "5")
--   10
--   
--   >>> maybe 0 (*2) (readMaybe "")
--   0
--   
-- -- Apply show to a Maybe Int. If we have Just n, -- we want to show the underlying Int n. But if we have -- Nothing, we return the empty string instead of (for example) -- "Nothing": -- --
--   >>> maybe "" show (Just 5)
--   "5"
--   
--   >>> maybe "" show Nothing
--   ""
--   
maybe :: b -> (a -> b) -> Maybe a -> b -- | The isJust function returns True iff its argument is of -- the form Just _. -- --

Examples

-- -- Basic usage: -- --
--   >>> isJust (Just 3)
--   True
--   
-- --
--   >>> isJust (Just ())
--   True
--   
-- --
--   >>> isJust Nothing
--   False
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isJust (Just Nothing)
--   True
--   
isJust :: Maybe a -> Bool -- | The isNothing function returns True iff its argument is -- Nothing. -- --

Examples

-- -- Basic usage: -- --
--   >>> isNothing (Just 3)
--   False
--   
-- --
--   >>> isNothing (Just ())
--   False
--   
-- --
--   >>> isNothing Nothing
--   True
--   
-- -- Only the outer constructor is taken into consideration: -- --
--   >>> isNothing (Just Nothing)
--   False
--   
isNothing :: Maybe a -> Bool -- | The maybeToList function returns an empty list when given -- Nothing or a singleton list when given Just. -- --

Examples

-- -- Basic usage: -- --
--   >>> maybeToList (Just 7)
--   [7]
--   
-- --
--   >>> maybeToList Nothing
--   []
--   
-- -- One can use maybeToList to avoid pattern matching when combined -- with a function that (safely) works on lists: -- --
--   >>> import Text.Read ( readMaybe )
--   
--   >>> sum $ maybeToList (readMaybe "3")
--   3
--   
--   >>> sum $ maybeToList (readMaybe "")
--   0
--   
maybeToList :: Maybe a -> [a] -- | The listToMaybe function returns Nothing on an empty -- list or Just a where a is the first element -- of the list. -- --

Examples

-- -- Basic usage: -- --
--   >>> listToMaybe []
--   Nothing
--   
-- --
--   >>> listToMaybe [9]
--   Just 9
--   
-- --
--   >>> listToMaybe [1,2,3]
--   Just 1
--   
-- -- Composing maybeToList with listToMaybe should be the -- identity on singleton/empty lists: -- --
--   >>> maybeToList $ listToMaybe [5]
--   [5]
--   
--   >>> maybeToList $ listToMaybe []
--   []
--   
-- -- But not on lists with more than one element: -- --
--   >>> maybeToList $ listToMaybe [1,2,3]
--   [1]
--   
listToMaybe :: [a] -> Maybe a -- | Safe version of tailEx, only working on non-nullable -- sequences. tail :: IsSequence seq => NonNull seq -> seq -- | Return the last element of a monomorphic container. -- -- Safe version of lastEx, only works on monomorphic containers -- wrapped in a NonNull. last :: MonoFoldable mono => NonNull mono -> Element mono -- | Safe version of initEx, only working on non-nullable -- sequences. init :: IsSequence seq => NonNull seq -> seq -- | Synonym for osum sum :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono -- | Synonym for oproduct product :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono -- | Get the maximum element of a monomorphic container. -- -- Safe version of maximumEx, only works on monomorphic containers -- wrapped in a NonNull. -- --

Examples

-- --
--   > let xs = ncons 1 [2, 3 :: Int]
--   > maximum xs
--   3
--   
maximum :: (MonoFoldable mono, Ord (Element mono)) => NonNull mono -> Element mono -- | Get the minimum element of a monomorphic container. -- -- Safe version of minimumEx, only works on monomorphic containers -- wrapped in a NonNull. -- --

Examples

-- --
--   > let xs = ncons 1 [2, 3 :: Int]
--   > minimum xs
--   1
--   
minimum :: (MonoFoldable mono, Ord (Element mono)) => NonNull mono -> Element mono -- | repeat x is an infinite list, with x the -- value of every element. -- --
--   >>> repeat 17
--   [17,17,17,17,17,17,17,17,17...
--   
repeat :: a -> [a] -- | Synonym for oand and :: (MonoFoldable mono, Element mono ~ Bool) => mono -> Bool -- | Synonym for oor or :: (MonoFoldable mono, Element mono ~ Bool) => mono -> Bool -- | Synonym for oany any :: MonoFoldable mono => (Element mono -> Bool) -> mono -> Bool -- | Synonym for oall all :: MonoFoldable mono => (Element mono -> Bool) -> mono -> Bool -- | Synonym for oelem elem :: (MonoFoldable mono, Eq (Element mono)) => Element mono -> mono -> Bool -- | Synonym for onotElem notElem :: (MonoFoldable mono, Eq (Element mono)) => Element mono -> mono -> Bool -- | Synonym for oconcatMap concatMap :: (MonoFoldable mono, Monoid m) => (Element mono -> m) -> mono -> m zip3 :: Zip3 f => f a -> f b -> f c -> f (a, b, c) zipWith3 :: Zip3 f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d unzip3 :: Zip3 f => f (a, b, c) -> (f a, f b, f c) odd :: Integral a => a -> Bool -- | raise a number to an integral power (^^) :: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^ -- | curry converts an uncurried function to a curried function. -- --

Examples

-- --
--   >>> curry fst 1 2
--   1
--   
curry :: ((a, b) -> c) -> a -> b -> c -- | Lifted newEmptyMVar. newEmptyMVar :: MonadIO m => m (MVar a) -- | Lifted newMVar. newMVar :: MonadIO m => a -> m (MVar a) -- | Lifted takeMVar. takeMVar :: MonadIO m => MVar a -> m a -- | Lifted readMVar. readMVar :: MonadIO m => MVar a -> m a -- | Lifted putMVar. putMVar :: MonadIO m => MVar a -> a -> m () -- | Lifted tryTakeMVar. tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted tryPutMVar. tryPutMVar :: MonadIO m => MVar a -> a -> m Bool -- | Lifted tryReadMVar. tryReadMVar :: MonadIO m => MVar a -> m (Maybe a) -- | Lifted isEmptyMVar. isEmptyMVar :: MonadIO m => MVar a -> m Bool -- | Flipped version of <$>. -- --
--   (<&>) = flip fmap
--   
-- --

Examples

-- -- Apply (+1) to a list, a Just and a Right: -- --
--   >>> Just 2 <&> (+1)
--   Just 3
--   
-- --
--   >>> [1,2,3] <&> (+1)
--   [2,3,4]
--   
-- --
--   >>> Right 3 <&> (+1)
--   Right 4
--   
(<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 <&> -- | on b u x y runs the binary function b -- on the results of applying unary function u to two -- arguments x and y. From the opposite perspective, it -- transforms two inputs and combines the outputs. -- --
--   ((+) `on` f) x y = f x + f y
--   
-- -- Typical usage: sortBy (compare `on` -- fst). -- -- Algebraic properties: -- -- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 `on` -- | One or none. -- -- It is useful for modelling any computation that is allowed to fail. -- --

Examples

-- -- Using the Alternative instance of Control.Monad.Except, -- the following functions: -- --
--   >>> import Control.Monad.Except
--   
-- --
--   >>> canFail = throwError "it failed" :: Except String Int
--   
--   >>> final = return 42                :: Except String Int
--   
-- -- Can be combined by allowing the first function to fail: -- --
--   >>> runExcept $ canFail *> final
--   Left "it failed"
--   
--   >>> runExcept $ optional canFail *> final
--   Right 42
--   
optional :: Alternative f => f a -> f (Maybe a) -- | Extracts from a list of Either all the Left elements. -- All the Left elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> lefts list
--   ["foo","bar","baz"]
--   
lefts :: [Either a b] -> [a] -- | Extracts from a list of Either all the Right elements. -- All the Right elements are extracted in order. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> rights list
--   [3,7]
--   
rights :: [Either a b] -> [b] -- | Partitions a list of Either into two lists. All the Left -- elements are extracted, in order, to the first component of the -- output. Similarly the Right elements are extracted to the -- second component of the output. -- --

Examples

-- -- Basic usage: -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list
--   (["foo","bar","baz"],[3,7])
--   
-- -- The pair returned by partitionEithers x should be the -- same pair as (lefts x, rights x): -- --
--   >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
--   
--   >>> partitionEithers list == (lefts list, rights list)
--   True
--   
partitionEithers :: [Either a b] -> ([a], [b]) -- |
--   comparing p x y = compare (p x) (p y)
--   
-- -- Useful combinator for use in conjunction with the xxxBy -- family of functions from Data.List, for example: -- --
--   ... sortBy (comparing fst) ...
--   
comparing :: Ord a => (b -> a) -> b -> b -> Ordering -- | Get the number of seconds which have passed since an arbitrary -- starting time, useful for calculating runtime in a program. getMonotonicTime :: MonadIO m => m Double -- | Synonym for ofold fold :: (MonoFoldable mono, Monoid (Element mono)) => mono -> Element mono -- | Synonym for ofoldMap foldMap :: (MonoFoldable mono, Monoid m) => (Element mono -> m) -> mono -> m -- | Synonym for ofoldlM foldlM :: (MonoFoldable mono, Monad m) => (a -> Element mono -> m a) -> a -> mono -> m a -- | Synonym for otraverse_ traverse_ :: (MonoFoldable mono, Applicative f) => (Element mono -> f b) -> mono -> f () -- | Synonym for ofor_ for_ :: (MonoFoldable mono, Applicative f) => mono -> (Element mono -> f b) -> f () -- | Synonym for osequence_ sequence_ :: (Applicative m, MonoFoldable mono, Element mono ~ m ()) => mono -> m () -- | The sum of a collection of actions using (<|>), -- generalizing concat. -- -- asum is just like msum, but generalised to -- Alternative. -- --

Examples

-- -- Basic usage: -- --
--   >>> asum [Just "Hello", Nothing, Just "World"]
--   Just "Hello"
--   
asum :: (Foldable t, Alternative f) => t (f a) -> f a -- | stripPrefix drops the given prefix from a sequence. It returns -- Nothing if the sequence did not start with the prefix given, or -- Just the sequence after the prefix, if it does. -- --
--   > stripPrefix "foo" "foobar"
--   Just "bar"
--   > stripPrefix "abc" "foobar"
--   Nothing
--   
stripPrefix :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> Maybe seq -- | isPrefixOf takes two sequences and returns True if the -- first sequence is a prefix of the second. isPrefixOf :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> Bool -- | isSuffixOf takes two sequences and returns True if the -- first sequence is a suffix of the second. isSuffixOf :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> Bool -- | isInfixOf takes two sequences and returns true if the -- first sequence is contained, wholly and intact, anywhere within the -- second. isInfixOf :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> Bool -- | An alias for difference. (\\) :: SetContainer a => a -> a -> a infixl 9 \\ -- | An alias for intersection. intersect :: SetContainer a => a -> a -> a -- | Synonym for ointercalate intercalate :: (MonoFoldable mono, Monoid (Element mono)) => Element mono -> mono -> Element mono -- | Insert a value, checking for conflicts with any unique constraints. If -- a duplicate exists in the database, it is returned as Left. -- Otherwise, the new 'Key is returned as Right. -- --

Example usage

-- -- With schema-2 and dataset-1, we have following lines of -- code: -- --
--   l1 <- insertBy $ User "SPJ" 20
--   l2 <- insertBy $ User "XXX" 41
--   l3 <- insertBy $ User "SPJ" 40
--   r1 <- insertBy $ User "XXX" 100
--   
-- -- First three lines return Left because there're duplicates in -- given record's uniqueness constraints. While the last line returns a -- new key as Right. insertBy :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record, SafeToInsert record) => record -> ReaderT backend m (Either (Entity record) (Key record)) zip4 :: Zip4 f => f a -> f b -> f c -> f d -> f (a, b, c, d) zipWith4 :: Zip4 f => (a -> b -> c -> d -> e) -> f a -> f b -> f c -> f d -> f e unzip4 :: Zip4 f => f (a, b, c, d) -> (f a, f b, f c, f d) zip5 :: Zip5 f => f a -> f b -> f c -> f d -> f e -> f (a, b, c, d, e) zipWith5 :: Zip5 f => (a -> b -> c -> d -> e -> g) -> f a -> f b -> f c -> f d -> f e -> f g unzip5 :: Zip5 f => f (a, b, c, d, e) -> (f a, f b, f c, f d, f e) zip6 :: Zip6 f => f a -> f b -> f c -> f d -> f e -> f g -> f (a, b, c, d, e, g) zipWith6 :: Zip6 f => (a -> b -> c -> d -> e -> g -> h) -> f a -> f b -> f c -> f d -> f e -> f g -> f h unzip6 :: Zip6 f => f (a, b, c, d, e, g) -> (f a, f b, f c, f d, f e, f g) zip7 :: Zip7 f => f a -> f b -> f c -> f d -> f e -> f g -> f h -> f (a, b, c, d, e, g, h) zipWith7 :: Zip7 f => (a -> b -> c -> d -> e -> g -> h -> i) -> f a -> f b -> f c -> f d -> f e -> f g -> f h -> f i unzip7 :: Zip7 f => f (a, b, c, d, e, g, h) -> (f a, f b, f c, f d, f e, f g, f h) -- | Construct an IOException value with a string describing the -- error. The fail method of the IO instance of the -- Monad class raises a userError, thus: -- --
--   instance Monad IO where
--     ...
--     fail s = ioError (userError s)
--   
userError :: String -> IOError -- | catch specialized to catch all synchronous exceptions. catchAny :: MonadUnliftIO m => m a -> (SomeException -> m a) -> m a -- | Like finally, but only call after if an exception -- occurs. onException :: MonadUnliftIO m => m a -> m b -> m a -- | Unlifted version of mask_. mask_ :: MonadUnliftIO m => m a -> m a -- | Unlifted version of uninterruptibleMask_. uninterruptibleMask_ :: MonadUnliftIO m => m a -> m a -- | Unlifted version of uninterruptibleMask. uninterruptibleMask :: MonadUnliftIO m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Lifted newIORef. newIORef :: MonadIO m => a -> m (IORef a) -- | Lifted readIORef. readIORef :: MonadIO m => IORef a -> m a -- | Lifted writeIORef. writeIORef :: MonadIO m => IORef a -> a -> m () -- | Unlifted mkWeakIORef. mkWeakIORef :: MonadUnliftIO m => IORef a -> m () -> m (Weak (IORef a)) -- | Lifted modifyIORef. modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () -- | Lifted modifyIORef'. modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () asyncExceptionToException :: Exception e => e -> SomeException asyncExceptionFromException :: Exception e => SomeException -> Maybe e -- | Raise an IOException in the IO monad. ioError :: IOError -> IO a -- | Send a value downstream to the next component to consume. If the -- downstream component terminates, this call will never return control. -- -- Since 0.5.0 yield :: forall (m :: Type -> Type) o i. Monad m => o -> ConduitT i o m () -- | Compose two alternative STM actions (GHC only). -- -- If the first action completes without retrying then it forms the -- result of the orElse. Otherwise, if the first action retries, -- then the second action is tried in its place. If both actions retry -- then the orElse as a whole retries. orElse :: STM a -> STM a -> STM a -- | Create a new TVar holding a value supplied newTVar :: a -> STM (TVar a) -- | Lifted version of newTVarIO newTVarIO :: MonadIO m => a -> m (TVar a) -- | Lifted version of readTVarIO readTVarIO :: MonadIO m => TVar a -> m a -- | Return the current value stored in a TVar. readTVar :: TVar a -> STM a -- | Write the supplied value into a TVar. writeTVar :: TVar a -> a -> STM () -- | Unlifted withMVar. withMVar :: MonadUnliftIO m => MVar a -> (a -> m b) -> m b -- | Unlifted modifyMVar_. modifyMVar_ :: MonadUnliftIO m => MVar a -> (a -> m a) -> m () -- | catchJust is like catch but it takes an extra argument -- which is an exception predicate, a function which selects which type -- of exceptions we're interested in. catchJust :: (MonadUnliftIO m, Exception e) => (e -> Maybe b) -> m a -> (b -> m a) -> m a -- | Flipped catchJust. handleJust :: (MonadUnliftIO m, Exception e) => (e -> Maybe b) -> (b -> m a) -> m a -> m a -- | A variant of try that takes an exception predicate to select -- which exceptions are caught. tryJust :: (MonadUnliftIO m, Exception e) => (e -> Maybe b) -> m a -> m (Either b a) -- | Same as bracket, but only perform the cleanup if an exception -- is thrown. bracketOnError :: MonadUnliftIO m => m a -> (a -> m b) -> (a -> m c) -> m c -- | Similar to catch, but provides multiple different handler -- functions. -- -- For more information on motivation, see base's -- catches. Note that, unlike that function, this function will -- not catch asynchronous exceptions. catches :: MonadUnliftIO m => m a -> [Handler m a] -> m a -- | Lifted swapMVar. swapMVar :: MonadIO m => MVar a -> a -> m a -- | Unlifted withMVarMasked. withMVarMasked :: MonadUnliftIO m => MVar a -> (a -> m b) -> m b -- | Unlifted modifyMVar. modifyMVar :: MonadUnliftIO m => MVar a -> (a -> m (a, b)) -> m b -- | Unlifted modifyMVarMasked_. modifyMVarMasked_ :: MonadUnliftIO m => MVar a -> (a -> m a) -> m () -- | Unlifted modifyMVarMasked. modifyMVarMasked :: MonadUnliftIO m => MVar a -> (a -> m (a, b)) -> m b -- | Unlifted mkWeakMVar. mkWeakMVar :: MonadUnliftIO m => MVar a -> m () -> m (Weak (MVar a)) -- | The construct tryIOError comp exposes IO errors which -- occur within a computation, and which are not fully handled. -- -- Non-I/O exceptions are not caught by this variant; to catch all -- exceptions, use try from Control.Exception. tryIOError :: IO a -> IO (Either IOError a) -- | Construct an IOException of the given type where the second -- argument describes the error location and the third and fourth -- argument contain the file handle and file path of the file involved in -- the error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | An error indicating that an IO operation failed because one of -- its arguments already exists. isAlreadyExistsError :: IOError -> Bool -- | A programmer-defined error value constructed using userError. isUserError :: IOError -> Bool -- | An error indicating that the operation failed because the resource -- vanished. See resourceVanishedErrorType. isResourceVanishedError :: IOError -> Bool -- | I/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments does -- not exist. doesNotExistErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType -- | I/O error where the operation failed because the device is full. fullErrorType :: IOErrorType -- | I/O error where the operation failed because the end of file has been -- reached. eofErrorType :: IOErrorType -- | I/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType -- | I/O error that is programmer-defined. userErrorType :: IOErrorType -- | I/O error where the operation failed because the resource vanished. -- This happens when, for example, attempting to write to a closed socket -- or attempting to write to a named pipe that was deleted. resourceVanishedErrorType :: IOErrorType -- | I/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments does -- not exist. isDoesNotExistErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because one of its arguments is a -- single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the end of file has been -- reached. isEOFErrorType :: IOErrorType -> Bool -- | I/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the user does not have -- sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool -- | I/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool -- | I/O error where the operation failed because the resource vanished. -- See resourceVanishedErrorType. isResourceVanishedErrorType :: IOErrorType -> Bool ioeGetErrorType :: IOError -> IOErrorType ioeGetErrorString :: IOError -> String ioeGetLocation :: IOError -> String ioeGetHandle :: IOError -> Maybe Handle ioeGetFileName :: IOError -> Maybe FilePath ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetFileName :: IOError -> FilePath -> IOError -- | Catch any IOException that occurs in the computation and throw -- a modified version. modifyIOError :: (IOError -> IOError) -> IO a -> IO a -- | Adds a location description and maybe a file path and file handle to -- an IOException. If any of the file handle or file path is not -- given the corresponding value in the IOException remains -- unaltered. annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError -- | Lifted version of registerDelay registerDelay :: MonadIO m => Int -> m (TVar Bool) -- | Unlifted version of withFile. withFile :: MonadUnliftIO m => FilePath -> IOMode -> (Handle -> m a) -> m a -- | Unlifted version of withBinaryFile. withBinaryFile :: MonadUnliftIO m => FilePath -> IOMode -> (Handle -> m a) -> m a -- | Lifted version of hFileSize hFileSize :: MonadIO m => Handle -> m Integer -- | Lifted version of hSetFileSize hSetFileSize :: MonadIO m => Handle -> Integer -> m () -- | Lifted version of hIsEOF hIsEOF :: MonadIO m => Handle -> m Bool -- | Lifted version of hSetBuffering hSetBuffering :: MonadIO m => Handle -> BufferMode -> m () -- | Lifted version of hTell hTell :: MonadIO m => Handle -> m Integer -- | Lifted version of hIsOpen hIsOpen :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsClosed hIsClosed :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsReadable hIsReadable :: MonadIO m => Handle -> m Bool -- | Lifted version of hIsWritable hIsWritable :: MonadIO m => Handle -> m Bool -- | Lifted version of hGetBuffering hGetBuffering :: MonadIO m => Handle -> m BufferMode -- | Lifted version of hIsSeekable hIsSeekable :: MonadIO m => Handle -> m Bool -- | Lifted version of hSetEcho hSetEcho :: MonadIO m => Handle -> Bool -> m () -- | Lifted version of hGetEcho hGetEcho :: MonadIO m => Handle -> m Bool -- | Write a character to stdout -- -- Uses system locale settings putChar :: MonadIO m => Char -> m () -- | Write a Text to stdout -- -- Uses system locale settings putStr :: MonadIO m => Text -> m () -- | Read a character from stdin -- -- Uses system locale settings getChar :: MonadIO m => m Char -- | Read all input from stdin into a lazy Text (LText) -- -- Uses system locale settings getContents :: MonadIO m => m LText -- | Takes a function of type 'LText -> LText' and passes all input on -- stdin to it, then prints result to stdout -- -- Uses lazy IO Uses system locale settings interact :: MonadIO m => (LText -> LText) -> m () -- | Strictly read a file into a ByteString. readFile :: MonadIO m => FilePath -> m ByteString -- | Lifted version of hReady hReady :: MonadIO m => Handle -> m Bool -- | Left-to-right composition of Kleisli arrows. -- -- '(bs >=> cs) a' can be understood as the -- do expression -- --
--   do b <- bs a
--      cs b
--   
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 >=> -- | Right-to-left composition of Kleisli arrows. -- (>=>), with the arguments flipped. -- -- Note how this operator resembles function composition -- (.): -- --
--   (.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
--   (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
--   
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c infixr 1 <=< -- | Synonym for ofoldM foldM :: (MonoFoldable mono, Monad m) => (a -> Element mono -> m a) -> a -> mono -> m a -- | Like replicateM, but discards the result. -- --

Examples

-- --
--   >>> replicateM_ 3 (putStrLn "a")
--   a
--   a
--   a
--   
replicateM_ :: Applicative m => Int -> m a -> m () -- | Since 0.5.9 traceShowM :: (Show a, Monad m) => a -> m () -- | Since 0.5.9 traceM :: Monad m => String -> m () -- | Since 0.5.9 traceShowId :: Show a => a -> a traceShow :: Show a => a -> b -> b -- | Since 0.5.9 traceId :: String -> String -- | Stream the contents of a file as binary data. sourceFile :: forall (m :: Type -> Type) i. MonadResource m => FilePath -> ConduitT i ByteString m () -- | Prepend an element to a non-null SemiSequence. (<|) :: SemiSequence seq => Element seq -> NonNull seq -> NonNull seq infixr 5 <| -- | Sort elements using the user supplied function to project something -- out of each element. Inspired by -- http://hackage.haskell.org/packages/archive/base/latest/doc/html/GHC-Exts.html#v:sortWith. sortWith :: (Ord a, IsSequence c) => (Element c -> a) -> c -> c -- | Lifted newQSemN. newQSemN :: MonadIO m => Int -> m QSemN -- | Lifted waitQSemN. waitQSemN :: MonadIO m => QSemN -> Int -> m () -- | Lifted signalQSemN. signalQSemN :: MonadIO m => QSemN -> Int -> m () -- | Lifted newQSem. newQSem :: MonadIO m => Int -> m QSem -- | Lifted waitQSem. waitQSem :: MonadIO m => QSem -> m () -- | Lifted signalQSem. signalQSem :: MonadIO m => QSem -> m () -- | Lifted newChan. newChan :: MonadIO m => m (Chan a) -- | Lifted writeChan. writeChan :: MonadIO m => Chan a -> a -> m () -- | Lifted readChan. readChan :: MonadIO m => Chan a -> m a -- | Lifted dupChan. dupChan :: MonadIO m => Chan a -> m (Chan a) -- | Lifted getChanContents. getChanContents :: MonadIO m => Chan a -> m [a] -- | Lifted writeList2Chan. writeList2Chan :: MonadIO m => Chan a -> [a] -> m () -- | Unlifted timeout. timeout :: MonadUnliftIO m => Int -> m a -> m (Maybe a) -- | Safely convert from a NonNull container to a -- NonEmpty list. toNonEmpty :: MonoFoldable mono => NonNull mono -> NonEmpty (Element mono) -- | a variant of deepseq that is useful in some circumstances: -- --
--   force x = x `deepseq` x
--   
-- -- force x fully evaluates x, and then returns it. Note -- that force x only performs evaluation when the value of -- force x itself is demanded, so essentially it turns shallow -- evaluation into deep evaluation. -- -- force can be conveniently used in combination with -- ViewPatterns: -- --
--   {-# LANGUAGE BangPatterns, ViewPatterns #-}
--   import Control.DeepSeq
--   
--   someFun :: ComplexData -> SomeResult
--   someFun (force -> !arg) = {- 'arg' will be fully evaluated -}
--   
-- -- Another useful application is to combine force with -- evaluate in order to force deep evaluation relative to other -- IO operations: -- --
--   import Control.Exception (evaluate)
--   import Control.DeepSeq
--   
--   main = do
--     result <- evaluate $ force $ pureComputation
--     {- 'result' will be fully evaluated at this point -}
--     return ()
--   
-- -- Finally, here's an exception safe variant of the readFile' -- example: -- --
--   readFile' :: FilePath -> IO String
--   readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
--                          evaluate . force =<< hGetContents h
--   
force :: NFData a => a -> a readIntegral :: Num a => String -> Maybe a -- | stripSuffix drops the given suffix from a sequence. It returns -- Nothing if the sequence did not end with the suffix given, or -- Just the sequence before the suffix, if it does. -- --
--   > stripSuffix "bar" "foobar"
--   Just "foo"
--   > stripSuffix "abc" "foobar"
--   Nothing
--   
stripSuffix :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> Maybe seq -- | Add an extension, even if there is already one there, equivalent to -- addExtension. -- --
--   "/directory/path" <.> "ext" == "/directory/path.ext"
--   "/directory/path" <.> ".ext" == "/directory/path.ext"
--   
(<.>) :: FilePath -> String -> FilePath infixr 7 <.> -- | Combine two paths with a path separator. If the second path starts -- with a path separator or a drive letter, then it returns the second. -- The intention is that readFile (dir </> file) -- will access the same file as setCurrentDirectory dir; readFile -- file. -- --
--   Posix:   "/directory" </> "file.ext" == "/directory/file.ext"
--   Windows: "/directory" </> "file.ext" == "/directory\\file.ext"
--            "directory" </> "/file.ext" == "/file.ext"
--   Valid x => (takeDirectory x </> takeFileName x) `equalFilePath` x
--   
-- -- Combined: -- --
--   Posix:   "/" </> "test" == "/test"
--   Posix:   "home" </> "bob" == "home/bob"
--   Posix:   "x:" </> "foo" == "x:/foo"
--   Windows: "C:\\foo" </> "bar" == "C:\\foo\\bar"
--   Windows: "home" </> "bob" == "home\\bob"
--   
-- -- Not combined: -- --
--   Posix:   "home" </> "/bob" == "/bob"
--   Windows: "home" </> "C:\\bob" == "C:\\bob"
--   
-- -- Not combined (tricky): -- -- On Windows, if a filepath starts with a single slash, it is relative -- to the root of the current drive. In [1], this is (confusingly) -- referred to as an absolute path. The current behavior of -- </> is to never combine these forms. -- --
--   Windows: "home" </> "/bob" == "/bob"
--   Windows: "home" </> "\\bob" == "\\bob"
--   Windows: "C:\\home" </> "\\bob" == "\\bob"
--   
-- -- On Windows, from [1]: "If a file name begins with only a disk -- designator but not the backslash after the colon, it is interpreted as -- a relative path to the current directory on the drive with the -- specified letter." The current behavior of </> is to -- never combine these forms. -- --
--   Windows: "D:\\foo" </> "C:bar" == "C:bar"
--   Windows: "C:\\foo" </> "C:bar" == "C:bar"
--   
() :: FilePath -> FilePath -> FilePath infixr 5 equating :: Eq a => (b -> a) -> b -> b -> Bool -- | error applied to Text -- -- Since 0.4.1 terror :: HasCallStack => Text -> a tshow :: Show a => a -> Text readMay :: (Element c ~ Char, MonoFoldable c, Read a) => c -> Maybe a hashPassword :: Text -> IO BCrypt toHtml :: ToMarkup a => a -> Html -- | Produce a Static based on embedding all of the static files' -- contents in the executable at compile time. -- -- You should use Yesod.EmbeddedStatic instead, it is much more -- powerful. -- -- Nota Bene: if you replace the scaffolded static call in -- Settings/StaticFiles.hs you will need to change the scaffolded -- addStaticContent. Otherwise, some of your assets will be 404'ed. This -- is because by default yesod will generate compile those assets to -- static/tmp which for static is fine since they are -- served out of the directory itself. With embedded static, that will -- not work. You can easily change addStaticContent to _ _ _ -- -> return Nothing as a workaround. This will cause yesod to -- embed those assets into the generated HTML file itself. embed :: FilePath -> Q Exp -- | Convert a value to Markup without escaping preEscapedToMarkup :: ToMarkup a => a -> Markup -- | Write a ByteString to the given Handle. hPut :: MonadIO m => Handle -> ByteString -> m () -- | Synonym for fromList pack :: IsSequence seq => [Element seq] -> seq -- | Synonym for otoList unpack :: MonoFoldable mono => mono -> [Element mono] -- | Synonym for ocompareLength compareLength :: (MonoFoldable mono, Integral i) => mono -> i -> Ordering -- | Provided for type disambiguation in the presence of OverloadedStrings. -- -- Since 0.1.0.0 textToBuilder :: ToBuilder Text builder => Text -> builder -- | Read a single chunk of data as a ByteString from the given -- Handle. -- -- Under the surface, this uses hGetSome with the default chunk -- size. hGetChunk :: MonadIO m => Handle -> m ByteString -- | the deep analogue of $!. In the expression f $!! x, -- x is fully evaluated before the function f is -- applied to it. ($!!) :: NFData a => (a -> b) -> a -> b infixr 0 $!! -- | Retrieves a function of the current environment. asks :: MonadReader r m => (r -> a) -> m a -- | Convert a PrimBase to another monad with the same state token. primToPrim :: (PrimBase m1, PrimMonad m2, PrimState m1 ~ PrimState m2) => m1 a -> m2 a -- | Convert a PrimBase with a RealWorld state token to -- IO primToIO :: (PrimBase m, PrimState m ~ RealWorld) => m a -> IO a -- | Convert a PrimBase to ST primToST :: PrimBase m => m a -> ST (PrimState m) a -- | Convert to proleptic Gregorian calendar. toGregorian :: Day -> (Year, MonthOfYear, DayOfMonth) -- | Convert from proleptic Gregorian calendar. Invalid values will be -- clipped to the correct range, month first, then day. fromGregorian :: Year -> MonthOfYear -> DayOfMonth -> Day -- | Locale representing American usage. -- -- knownTimeZones contains only the ten time-zones mentioned in -- RFC 822 sec. 5: "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", -- "PST", "PDT". Note that the parsing functions will regardless parse -- "UTC", single-letter military time-zones, and +HHMM format. defaultTimeLocale :: TimeLocale -- | Substitute various time-related information for each %-code in the -- string, as per formatCharacter. -- -- The general form is -- %<modifier><width><alternate><specifier>, -- where <modifier>, <width>, and -- <alternate> are optional. -- --

<modifier>

-- -- glibc-style modifiers can be used before the specifier (here marked as -- z): -- -- -- --

<width>

-- -- Width digits can also be used after any modifiers and before the -- specifier (here marked as z), for example: -- -- -- --

<alternate>

-- -- An optional E character indicates an alternate formatting. -- Currently this only affects %Z and %z. -- -- -- --

<specifier>

-- -- For all types (note these three are done by formatTime, not by -- formatCharacter): -- -- -- --

TimeZone

-- -- For TimeZone (and ZonedTime and UTCTime): -- -- -- --

LocalTime

-- -- For LocalTime (and ZonedTime and UTCTime -- and UniversalTime): -- -- -- --

TimeOfDay

-- -- For TimeOfDay (and LocalTime and ZonedTime -- and UTCTime and UniversalTime): -- -- -- --

UTCTime and ZonedTime

-- -- For UTCTime and ZonedTime: -- -- -- --

DayOfWeek

-- -- For DayOfWeek (and Day and LocalTime and -- ZonedTime and UTCTime and UniversalTime): -- -- -- --

Month

-- -- For Month (and Day and LocalTime and -- ZonedTime and UTCTime and UniversalTime): -- -- -- --

Day

-- -- For Day (and LocalTime and ZonedTime and -- UTCTime and UniversalTime): -- -- -- --

Duration types

-- -- The specifiers for DiffTime, NominalDiffTime, -- CalendarDiffDays, and CalendarDiffTime are -- semantically separate from the other types. Specifiers on negative -- time differences will generally be negative (think rem rather -- than mod). -- --

NominalDiffTime and DiffTime

-- -- Note that a "minute" of DiffTime is simply 60 SI seconds, -- rather than a minute of civil time. Use NominalDiffTime to -- work with civil time, ignoring any leap seconds. -- -- For NominalDiffTime and DiffTime: -- -- -- --

CalendarDiffDays

-- -- For CalendarDiffDays (and CalendarDiffTime): -- -- -- --

CalendarDiffTime

-- -- For CalendarDiffTime: -- -- formatTime :: FormatTime t => TimeLocale -> String -> t -> String -- | Parses a time value given a format string. Missing information will be -- derived from 1970-01-01 00:00 UTC (which was a Thursday). Supports the -- same %-codes as formatTime, including %-, -- %_ and %0 modifiers, however padding widths are not -- supported. Case is not significant in the input string. Some -- variations in the input are accepted: -- -- -- -- For example, to parse a date in YYYY-MM-DD format, while allowing the -- month and date to have optional leading zeros (notice the - -- modifier used for %m and %d): -- --
--   Prelude Data.Time> parseTimeM True defaultTimeLocale "%Y-%-m-%-d" "2010-3-04" :: Maybe Day
--   Just 2010-03-04
--   
parseTimeM :: (MonadFail m, ParseTime t) => Bool -> TimeLocale -> String -> String -> m t tlshow :: Show a => a -> LText -- | Convert a character to lower case. -- -- Character-based case conversion is lossy in comparison to string-based -- toLower. For instance, İ will be converted to i, instead of i̇. charToLower :: Char -> Char -- | Convert a character to upper case. -- -- Character-based case conversion is lossy in comparison to string-based -- toUpper. For instance, ß won't be converted to SS. charToUpper :: Char -> Char asByteString :: ByteString -> ByteString asLByteString :: LByteString -> LByteString asHashMap :: HashMap k v -> HashMap k v asHashSet :: HashSet a -> HashSet a asText :: Text -> Text asLText :: LText -> LText asList :: [a] -> [a] asMap :: Map k v -> Map k v asIntMap :: IntMap v -> IntMap v asMaybe :: Maybe a -> Maybe a asSet :: Set a -> Set a asIntSet :: IntSet -> IntSet asVector :: Vector a -> Vector a asUVector :: UVector a -> UVector a asSVector :: SVector a -> SVector a asString :: [Char] -> [Char] -- | Originally yield. yieldThread :: MonadIO m => m () -- | same behavior as nub, but requires Hashable & -- Eq and is O(n log n) -- -- https://github.com/nh2/haskell-ordnub hashNub :: (Hashable a, Eq a) => [a] -> [a] -- | same behavior as nub, but requires Ord and is O(n -- log n) -- -- https://github.com/nh2/haskell-ordnub ordNub :: Ord a => [a] -> [a] -- | same behavior as nubBy, but requires Ord and is O(n -- log n) -- -- https://github.com/nh2/haskell-ordnub ordNubBy :: Ord b => (a -> b) -> (a -> a -> Bool) -> [a] -> [a] -- | Synonym for orElse. orElseSTM :: STM a -> STM a -> STM a -- | Only perform the action if the predicate returns True. -- -- Since 0.9.2 whenM :: Monad m => m Bool -> m () -> m () -- | Only perform the action if the predicate returns False. -- -- Since 0.9.2 unlessM :: Monad m => m Bool -> m () -> m () -- | Force type to a DList -- -- Since 0.11.0 asDList :: DList a -> DList a -- | Synonym for apply -- -- Since 0.11.0 applyDList :: DList a -> [a] -> [a] -- | && lifted to an Applicative. (<&&>) :: Applicative a => a Bool -> a Bool -> a Bool infixr 3 <&&> -- | || lifted to an Applicative. (<||>) :: Applicative a => a Bool -> a Bool -> a Bool infixr 2 <||> -- | Convert a ByteString into a storable Vector. toByteVector :: ByteString -> SVector Word8 -- | Convert a storable Vector into a ByteString. fromByteVector :: SVector Word8 -> ByteString -- | waitSTM for any MonadIO waitAsync :: MonadIO m => Async a -> m a -- | pollSTM for any MonadIO pollAsync :: MonadIO m => Async a -> m (Maybe (Either SomeException a)) -- | waitCatchSTM for any MonadIO waitCatchAsync :: MonadIO m => Async a -> m (Either SomeException a) -- | link generalized to any MonadIO linkAsync :: MonadIO m => Async a -> m () -- | link2 generalized to any MonadIO link2Async :: MonadIO m => Async a -> Async b -> m () -- | Strictly read a file into a Text using a UTF-8 character -- encoding. In the event of a character encoding error, a Unicode -- replacement character will be used (a.k.a., lenientDecode). readFileUtf8 :: MonadIO m => FilePath -> m Text -- | Write a Text to a file using a UTF-8 character encoding. writeFileUtf8 :: MonadIO m => FilePath -> Text -> m () parseTime :: ParseTime t => TimeLocale -> String -> String -> Maybe t -- | A convenience function for throwing a user error. This is useful for -- cases where it would be too high a burden to define your own exception -- type. -- -- This throws an exception of type StringException. When GHC -- supports it (base 4.9 and GHC 8.0 and onward), it includes a call -- stack. throwString :: (MonadIO m, HasCallStack) => String -> m a -- | Generate a pure value which, when forced, will synchronously throw the -- given exception. -- -- Generally it's better to avoid using this function and instead use -- throwIO, see -- https://github.com/fpco/safe-exceptions#quickstart. impureThrow :: Exception e => e -> a -- | catch specialized to only catching IOExceptions. catchIO :: MonadUnliftIO m => m a -> (IOException -> m a) -> m a -- | Same as catch, but fully force evaluation of the result value -- to find all impure exceptions. catchDeep :: (MonadUnliftIO m, Exception e, NFData a) => m a -> (e -> m a) -> m a -- | catchDeep specialized to catch all synchronous exception. catchAnyDeep :: (NFData a, MonadUnliftIO m) => m a -> (SomeException -> m a) -> m a -- | handle specialized to only catching IOExceptions. handleIO :: MonadUnliftIO m => (IOException -> m a) -> m a -> m a -- | Flipped version of catchAny. handleAny :: MonadUnliftIO m => (SomeException -> m a) -> m a -> m a -- | Flipped version of catchDeep. handleDeep :: (MonadUnliftIO m, Exception e, NFData a) => (e -> m a) -> m a -> m a -- | Flipped version of catchAnyDeep. handleAnyDeep :: (MonadUnliftIO m, NFData a) => (SomeException -> m a) -> m a -> m a -- | try specialized to only catching IOExceptions. tryIO :: MonadUnliftIO m => m a -> m (Either IOException a) -- | try specialized to catch all synchronous exceptions. tryAny :: MonadUnliftIO m => m a -> m (Either SomeException a) -- | Same as try, but fully force evaluation of the result value to -- find all impure exceptions. tryDeep :: (MonadUnliftIO m, Exception e, NFData a) => m a -> m (Either e a) -- | tryDeep specialized to catch all synchronous exceptions. tryAnyDeep :: (MonadUnliftIO m, NFData a) => m a -> m (Either SomeException a) -- | Like onException, but provides the handler the thrown -- exception. withException :: (MonadUnliftIO m, Exception e) => m a -> (e -> m b) -> m a -- | A variant of bracketOnError where the return value from the -- first computation is not required. bracketOnError_ :: MonadUnliftIO m => m a -> m b -> m c -> m c -- | Convert an exception into a synchronous exception. -- -- For synchronous exceptions, this is the same as toException. -- For asynchronous exceptions, this will wrap up the exception with -- SyncExceptionWrapper. toSyncException :: Exception e => e -> SomeException -- | Convert an exception into an asynchronous exception. -- -- For asynchronous exceptions, this is the same as toException. -- For synchronous exceptions, this will wrap up the exception with -- AsyncExceptionWrapper. toAsyncException :: Exception e => e -> SomeException -- | Check if the given exception is synchronous. isSyncException :: Exception e => e -> Bool -- | Check if the given exception is asynchronous. isAsyncException :: Exception e => e -> Bool -- | Same as catches, but fully force evaluation of the result value -- to find all impure exceptions. catchesDeep :: (MonadUnliftIO m, NFData a) => m a -> [Handler m a] -> m a -- | Deeply evaluate a value using evaluate and NFData. evaluateDeep :: (MonadIO m, NFData a) => a -> m a -- | Builds and returns a new instance of TBQueue. newTBQueue :: Natural -> STM (TBQueue a) -- | Write a value to a TBQueue; blocks if the queue is full. writeTBQueue :: TBQueue a -> a -> STM () -- | Read the next value from the TBQueue. readTBQueue :: TBQueue a -> STM a -- | A version of readTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTBQueue :: TBQueue a -> STM (Maybe a) -- | Efficiently read the entire contents of a TBQueue into a list. -- This function never retries. flushTBQueue :: TBQueue a -> STM [a] -- | Get the next value from the TBQueue without removing it, -- retrying if the channel is empty. peekTBQueue :: TBQueue a -> STM a -- | A version of peekTBQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTBQueue :: TBQueue a -> STM (Maybe a) -- | Put a data item back onto a channel, where it will be the next item -- read. Blocks if the queue is full. unGetTBQueue :: TBQueue a -> a -> STM () -- | Return the length of a TBQueue. lengthTBQueue :: TBQueue a -> STM Natural -- | Returns True if the supplied TBQueue is empty. isEmptyTBQueue :: TBQueue a -> STM Bool -- | Returns True if the supplied TBQueue is full. isFullTBQueue :: TBQueue a -> STM Bool -- | Build and return a new instance of TChan newTChan :: STM (TChan a) -- | Create a write-only TChan. More precisely, readTChan -- will retry even after items have been written to the channel. -- The only way to read a broadcast channel is to duplicate it with -- dupTChan. -- -- Consider a server that broadcasts messages to clients: -- --
--   serve :: TChan Message -> Client -> IO loop
--   serve broadcastChan client = do
--       myChan <- dupTChan broadcastChan
--       forever $ do
--           message <- readTChan myChan
--           send client message
--   
-- -- The problem with using newTChan to create the broadcast channel -- is that if it is only written to and never read, items will pile up in -- memory. By using newBroadcastTChan to create the broadcast -- channel, items can be garbage collected after clients have seen them. newBroadcastTChan :: STM (TChan a) -- | Write a value to a TChan. writeTChan :: TChan a -> a -> STM () -- | Read the next value from the TChan. readTChan :: TChan a -> STM a -- | A version of readTChan which does not retry. Instead it returns -- Nothing if no value is available. tryReadTChan :: TChan a -> STM (Maybe a) -- | Get the next value from the TChan without removing it, -- retrying if the channel is empty. peekTChan :: TChan a -> STM a -- | A version of peekTChan which does not retry. Instead it returns -- Nothing if no value is available. tryPeekTChan :: TChan a -> STM (Maybe a) -- | Duplicate a TChan: the duplicate channel begins empty, but data -- written to either channel from then on will be available from both. -- Hence this creates a kind of broadcast channel, where data written by -- anyone is seen by everyone else. dupTChan :: TChan a -> STM (TChan a) -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTChan :: TChan a -> a -> STM () -- | Returns True if the supplied TChan is empty. isEmptyTChan :: TChan a -> STM Bool -- | Clone a TChan: similar to dupTChan, but the cloned channel -- starts with the same content available as the original channel. cloneTChan :: TChan a -> STM (TChan a) -- | Create a TMVar which contains the supplied value. newTMVar :: a -> STM (TMVar a) -- | Create a TMVar which is initially empty. newEmptyTMVar :: STM (TMVar a) -- | Lifted version of newEmptyTMVarIO newEmptyTMVarIO :: MonadIO m => m (TMVar a) -- | Return the contents of the TMVar. If the TMVar is -- currently empty, the transaction will retry. After a -- takeTMVar, the TMVar is left empty. takeTMVar :: TMVar a -> STM a -- | A version of takeTMVar that does not retry. The -- tryTakeTMVar function returns Nothing if the -- TMVar was empty, or Just a if the TMVar -- was full with contents a. After tryTakeTMVar, the -- TMVar is left empty. tryTakeTMVar :: TMVar a -> STM (Maybe a) -- | Put a value into a TMVar. If the TMVar is currently -- full, putTMVar will retry. putTMVar :: TMVar a -> a -> STM () -- | A version of putTMVar that does not retry. The -- tryPutTMVar function attempts to put the value a into -- the TMVar, returning True if it was successful, or -- False otherwise. tryPutTMVar :: TMVar a -> a -> STM Bool -- | This is a combination of takeTMVar and putTMVar; ie. it -- takes the value from the TMVar, puts it back, and also returns -- it. readTMVar :: TMVar a -> STM a -- | A version of readTMVar which does not retry. Instead it returns -- Nothing if no value is available. tryReadTMVar :: TMVar a -> STM (Maybe a) -- | Swap the contents of a TMVar for a new value. swapTMVar :: TMVar a -> a -> STM a -- | Non-blocking write of a new value to a TMVar Puts if empty. -- Replaces if populated. writeTMVar :: TMVar a -> a -> STM () -- | Check whether a given TMVar is empty. isEmptyTMVar :: TMVar a -> STM Bool -- | Lifted version of mkWeakTMVar mkWeakTMVar :: MonadUnliftIO m => TMVar a -> m () -> m (Weak (TMVar a)) -- | Build and returns a new instance of TQueue newTQueue :: STM (TQueue a) -- | Write a value to a TQueue. writeTQueue :: TQueue a -> a -> STM () -- | Read the next value from the TQueue. readTQueue :: TQueue a -> STM a -- | A version of readTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryReadTQueue :: TQueue a -> STM (Maybe a) -- | Get the next value from the TQueue without removing it, -- retrying if the channel is empty. peekTQueue :: TQueue a -> STM a -- | A version of peekTQueue which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTQueue :: TQueue a -> STM (Maybe a) -- | Put a data item back onto a channel, where it will be the next item -- read. unGetTQueue :: TQueue a -> a -> STM () -- | Returns True if the supplied TQueue is empty. isEmptyTQueue :: TQueue a -> STM Bool -- | Mutate the contents of a TVar. N.B., this version is -- non-strict. modifyTVar :: TVar a -> (a -> a) -> STM () -- | Strict version of modifyTVar. modifyTVar' :: TVar a -> (a -> a) -> STM () -- | Like modifyTVar' but the function is a simple state transition -- that can return a side value which is passed on as the result of the -- STM. stateTVar :: TVar s -> (s -> (a, s)) -> STM a -- | Swap the contents of a TVar for a new value. swapTVar :: TVar a -> a -> STM a -- | Lifted version of mkWeakTVar mkWeakTVar :: MonadUnliftIO m => TVar a -> m () -> m (Weak (TVar a)) -- | A variant of catch that catches both synchronous and -- asynchronous exceptions. -- -- WARNING: This function (and other *SyncOrAsync functions) is -- for advanced users. Most of the time, you probably want to use the -- non-SyncOrAsync versions. -- -- Before attempting to use this function, be familiar with the "Rules -- for async safe handling" section in this blog post. catchSyncOrAsync :: (MonadUnliftIO m, Exception e) => m a -> (e -> m a) -> m a -- | A variant of handle that catches both synchronous and -- asynchronous exceptions. -- -- See catchSyncOrAsync. handleSyncOrAsync :: (MonadUnliftIO m, Exception e) => (e -> m a) -> m a -> m a -- | A variant of try that catches both synchronous and asynchronous -- exceptions. -- -- See catchSyncOrAsync. trySyncOrAsync :: (MonadUnliftIO m, Exception e) => m a -> m (Either e a) -- | Evaluate the value to WHNF and catch any synchronous exceptions. -- -- The expression may still have bottom values within it; you may instead -- want to use pureTryDeep. pureTry :: a -> Either SomeException a -- | Evaluate the value to NF and catch any synchronous exceptions. pureTryDeep :: NFData a => a -> Either SomeException a -- | Convert from a possibly wrapped exception. -- -- The inverse of toAsyncException and toSyncException. -- When using those functions (or functions that use them, like -- throwTo or throwIO), fromException might not be -- sufficient because the exception might be wrapped within -- SyncExceptionWrapper or AsyncExceptionWrapper. fromExceptionUnwrap :: Exception e => SomeException -> Maybe e -- | Smart constructor for a StringException that deals with the -- call stack. stringException :: HasCallStack => String -> StringException -- | Unwrap an Either value, throwing its Left value as a -- runtime exception via throwIO if present. fromEither :: (Exception e, MonadIO m) => Either e a -> m a -- | Same as fromEither, but works on an IO-wrapped -- Either. fromEitherIO :: (Exception e, MonadIO m) => IO (Either e a) -> m a -- | Same as fromEither, but works on an m-wrapped -- Either. fromEitherM :: (Exception e, MonadIO m) => m (Either e a) -> m a -- | Same as mapException, except works in a monadic context. mapExceptionM :: (Exception e1, Exception e2, MonadUnliftIO m) => (e1 -> e2) -> m a -> m a -- | Construct a value of type Conc from an action. Compose these -- values using the typeclass instances (most commonly Applicative -- and Alternative) and then run with runConc. conc :: m a -> Conc m a -- | Run a Conc value on multiple threads. runConc :: MonadUnliftIO m => Conc m a -> m a -- | Like mapConcurrently from async, but instead of one thread per -- element, it does pooling from a set of threads. This is useful in -- scenarios where resource consumption is bounded and for use cases -- where too many concurrent tasks aren't allowed. -- --

Example usage

-- --
--   import Say
--   
--   action :: Int -> IO Int
--   action n = do
--     tid <- myThreadId
--     sayString $ show tid
--     threadDelay (2 * 10^6) -- 2 seconds
--     return n
--   
--   main :: IO ()
--   main = do
--     yx <- pooledMapConcurrentlyN 5 (\x -> action x) [1..5]
--     print yx
--   
-- -- On executing you can see that five threads have been spawned: -- --
--   $ ./pool
--   ThreadId 36
--   ThreadId 38
--   ThreadId 40
--   ThreadId 42
--   ThreadId 44
--   [1,2,3,4,5]
--   
-- -- Let's modify the above program such that there are less threads than -- the number of items in the list: -- --
--   import Say
--   
--   action :: Int -> IO Int
--   action n = do
--     tid <- myThreadId
--     sayString $ show tid
--     threadDelay (2 * 10^6) -- 2 seconds
--     return n
--   
--   main :: IO ()
--   main = do
--     yx <- pooledMapConcurrentlyN 3 (\x -> action x) [1..5]
--     print yx
--   
-- -- On executing you can see that only three threads are active totally: -- --
--   $ ./pool
--   ThreadId 35
--   ThreadId 37
--   ThreadId 39
--   ThreadId 35
--   ThreadId 39
--   [1,2,3,4,5]
--   
pooledMapConcurrentlyN :: (MonadUnliftIO m, Traversable t) => Int -> (a -> m b) -> t a -> m (t b) -- | Similar to pooledMapConcurrentlyN but with number of threads -- set from getNumCapabilities. Usually this is useful for CPU -- bound tasks. pooledMapConcurrently :: (MonadUnliftIO m, Traversable t) => (a -> m b) -> t a -> m (t b) -- | Similar to pooledMapConcurrentlyN but with flipped arguments. pooledForConcurrentlyN :: (MonadUnliftIO m, Traversable t) => Int -> t a -> (a -> m b) -> m (t b) -- | Similar to pooledForConcurrentlyN but with number of threads -- set from getNumCapabilities. Usually this is useful for CPU -- bound tasks. pooledForConcurrently :: (MonadUnliftIO m, Traversable t) => t a -> (a -> m b) -> m (t b) -- | Like pooledMapConcurrentlyN but with the return value -- discarded. pooledMapConcurrentlyN_ :: (MonadUnliftIO m, Foldable f) => Int -> (a -> m b) -> f a -> m () -- | Like pooledMapConcurrently but with the return value discarded. pooledMapConcurrently_ :: (MonadUnliftIO m, Foldable f) => (a -> m b) -> f a -> m () -- | Like pooledMapConcurrently_ but with flipped arguments. pooledForConcurrently_ :: (MonadUnliftIO m, Foldable f) => f a -> (a -> m b) -> m () -- | Like pooledMapConcurrentlyN_ but with flipped arguments. pooledForConcurrentlyN_ :: (MonadUnliftIO m, Foldable t) => Int -> t a -> (a -> m b) -> m () -- | Pooled version of replicateConcurrently. Performs the action in -- the pooled threads. pooledReplicateConcurrentlyN :: MonadUnliftIO m => Int -> Int -> m a -> m [a] -- | Similar to pooledReplicateConcurrentlyN but with number of -- threads set from getNumCapabilities. Usually this is useful for -- CPU bound tasks. pooledReplicateConcurrently :: MonadUnliftIO m => Int -> m a -> m [a] -- | Pooled version of replicateConcurrently_. Performs the action -- in the pooled threads. pooledReplicateConcurrentlyN_ :: MonadUnliftIO m => Int -> Int -> m a -> m () -- | Similar to pooledReplicateConcurrently_ but with number of -- threads set from getNumCapabilities. Usually this is useful for -- CPU bound tasks. pooledReplicateConcurrently_ :: MonadUnliftIO m => Int -> m a -> m () -- | Extract a value from a Memoized, running an action if no cached -- value is available. runMemoized :: MonadIO m => Memoized a -> m a -- | Create a new Memoized value using an IORef under the -- surface. Note that the action may be run in multiple threads -- simultaneously, so this may not be thread safe (depending on the -- underlying action). Consider using memoizeMVar. memoizeRef :: MonadUnliftIO m => m a -> m (Memoized a) -- | Same as memoizeRef, but uses an MVar to ensure that an -- action is only run once, even in a multithreaded application. memoizeMVar :: MonadUnliftIO m => m a -> m (Memoized a) -- | withQSem is an exception-safe wrapper for performing the -- provided operation while holding a unit of value from the semaphore. -- It ensures the semaphore cannot be leaked if there are exceptions. withQSem :: MonadUnliftIO m => QSem -> m a -> m a -- | withQSemN is an exception-safe wrapper for performing the -- provided operation while holding N unit of value from the semaphore. -- It ensures the semaphore cannot be leaked if there are exceptions. withQSemN :: MonadUnliftIO m => QSemN -> Int -> m a -> m a -- | Renamed retry for unqualified export retrySTM :: STM a -- | Renamed check for unqualified export checkSTM :: Bool -> STM () -- | Create and use a temporary file in the system standard temporary -- directory. -- -- Behaves exactly the same as withTempFile, except that the -- parent temporary directory will be that returned by -- getCanonicalTemporaryDirectory. withSystemTempFile :: MonadUnliftIO m => String -> (FilePath -> Handle -> m a) -> m a -- | Create and use a temporary directory in the system standard temporary -- directory. -- -- Behaves exactly the same as withTempDirectory, except that the -- parent temporary directory will be that returned by -- getCanonicalTemporaryDirectory. withSystemTempDirectory :: MonadUnliftIO m => String -> (FilePath -> m a) -> m a -- | Use a temporary filename that doesn't already exist. -- -- Creates a new temporary file inside the given directory, making use of -- the template. The temp file is deleted after use. For example: -- --
--   withTempFile "src" "sdist." $ \tmpFile hFile -> do ...
--   
-- -- The tmpFile will be file in the given directory, e.g. -- src/sdist.342. withTempFile :: MonadUnliftIO m => FilePath -> String -> (FilePath -> Handle -> m a) -> m a -- | Create and use a temporary directory. -- -- Creates a new temporary directory inside the given directory, making -- use of the template. The temp directory is deleted after use. For -- example: -- --
--   withTempDirectory "src" "sdist." $ \tmpDir -> do ...
--   
-- -- The tmpDir will be a new subdirectory of the given directory, -- e.g. src/sdist.342. withTempDirectory :: MonadUnliftIO m => FilePath -> String -> (FilePath -> m a) -> m a -- | Capture the current monadic context, providing the ability to run -- monadic actions in IO. -- -- See UnliftIO for an explanation of why we need a helper -- datatype here. -- -- Prior to version 0.2.0.0 of this library, this was a method in the -- MonadUnliftIO type class. It was moved out due to -- https://github.com/fpco/unliftio/issues/55. askUnliftIO :: MonadUnliftIO m => m (UnliftIO m) -- | Same as askUnliftIO, but returns a monomorphic function instead -- of a polymorphic newtype wrapper. If you only need to apply the -- transformation on one concrete type, this function can be more -- convenient. askRunInIO :: MonadUnliftIO m => m (m a -> IO a) -- | Convenience function for capturing the monadic context and running an -- IO action. The UnliftIO newtype wrapper is rarely -- needed, so prefer withRunInIO to this function. withUnliftIO :: MonadUnliftIO m => (UnliftIO m -> IO a) -> m a -- | Convert an action in m to an action in IO. toIO :: MonadUnliftIO m => m a -> m (IO a) -- | A helper function for implementing MonadUnliftIO instances. -- Useful for the common case where you want to simply delegate to the -- underlying transformer. -- -- Note: You can derive MonadUnliftIO for newtypes without this -- helper function in unliftio-core 0.2.0.0 and later. -- --

Example

-- --
--   newtype AppT m a = AppT { unAppT :: ReaderT Int (ResourceT m) a }
--     deriving (Functor, Applicative, Monad, MonadIO)
--   
--   -- Same as `deriving newtype (MonadUnliftIO)`
--   instance MonadUnliftIO m => MonadUnliftIO (AppT m) where
--     withRunInIO = wrappedWithRunInIO AppT unAppT
--   
wrappedWithRunInIO :: MonadUnliftIO n => (n b -> m b) -> (forall a. () => m a -> n a) -> ((forall a. () => m a -> IO a) -> IO b) -> m b -- | A helper function for lifting IO a -> IO b functions into -- any MonadUnliftIO. -- --

Example

-- --
--   liftedTry :: (Exception e, MonadUnliftIO m) => m a -> m (Either e a)
--   liftedTry m = liftIOOp Control.Exception.try m
--   
liftIOOp :: MonadUnliftIO m => (IO a -> IO b) -> m a -> m b -- | Since 0.2.0 asIORef :: IORef a -> IORef a -- | Since 0.2.0 asSTRef :: STRef s a -> STRef s a -- | Since 0.2.0 asMutVar :: MutVar s a -> MutVar s a -- | Since 0.2.0 asBRef :: BRef s a -> BRef s a -- | Since 0.2.0 asDLList :: DLList s a -> DLList s a -- | Since 0.2.0 asUDeque :: UDeque s a -> UDeque s a -- | Since 0.2.0 asSDeque :: SDeque s a -> SDeque s a -- | Since 0.2.0 asBDeque :: BDeque s a -> BDeque s a -- | Since 0.2.0 asPRef :: PRef s a -> PRef s a -- | Since 0.2.0 asSRef :: SRef s a -> SRef s a -- | Since 0.2.0 asURef :: URef s a -> URef s a -- | Build and returns a new instance of TBChan with the given -- capacity. N.B., we do not verify the capacity is positive, but -- if it is non-positive then writeTBChan will always retry and -- isFullTBChan will always be true. newTBChan :: Int -> STM (TBChan a) -- | IO version of newTBChan. This is useful for creating -- top-level TBChans using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTBChanIO :: Int -> IO (TBChan a) -- | Read the next value from the TBChan, retrying if the channel -- is empty. readTBChan :: TBChan a -> STM a -- | A version of readTBChan which does not retry. Instead it -- returns Nothing if no value is available. tryReadTBChan :: TBChan a -> STM (Maybe a) -- | Get the next value from the TBChan without removing it, -- retrying if the channel is empty. peekTBChan :: TBChan a -> STM a -- | A version of peekTBChan which does not retry. Instead it -- returns Nothing if no value is available. tryPeekTBChan :: TBChan a -> STM (Maybe a) -- | Write a value to a TBChan, retrying if the channel is full. writeTBChan :: TBChan a -> a -> STM () -- | A version of writeTBChan which does not retry. Returns -- True if the value was successfully written, and -- False otherwise. tryWriteTBChan :: TBChan a -> a -> STM Bool -- | Put a data item back onto a channel, where it will be the next item -- read. N.B., this could allow the channel to temporarily become -- longer than the specified limit, which is necessary to ensure that the -- item is indeed the next one read. unGetTBChan :: TBChan a -> a -> STM () -- | Returns True if the supplied TBChan is empty (i.e., -- has no elements). N.B., a TBChan can be both "empty" -- and "full" at the same time, if the initial limit was non-positive. isEmptyTBChan :: TBChan a -> STM Bool -- | Returns True if the supplied TBChan is full (i.e., -- is over its limit). N.B., a TBChan can be both "empty" -- and "full" at the same time, if the initial limit was non-positive. -- N.B., a TBChan may still be full after reading, if -- unGetTBChan was used to go over the initial limit. -- -- This is equivalent to: liftM (<= 0) -- estimateFreeSlotsTBMChan isFullTBChan :: TBChan a -> STM Bool -- | Estimate the number of free slots. If the result is positive, then -- it's a minimum bound; if it's non-positive then it's exact. It will -- only be negative if the initial limit was negative or if -- unGetTBChan was used to go over the initial limit. -- -- This function always contends with writers, but only contends with -- readers when it has to; compare against freeSlotsTBChan. estimateFreeSlotsTBChan :: TBChan a -> STM Int -- | Return the exact number of free slots. The result can be negative if -- the initial limit was negative or if unGetTBChan was used to go -- over the initial limit. -- -- This function always contends with both readers and writers; compare -- against estimateFreeSlotsTBChan. freeSlotsTBChan :: TBChan a -> STM Int -- | Build and returns a new instance of TBMChan with the given -- capacity. N.B., we do not verify the capacity is positive, but -- if it is non-positive then writeTBMChan will always retry and -- isFullTBMChan will always be true. newTBMChan :: Int -> STM (TBMChan a) -- | IO version of newTBMChan. This is useful for creating -- top-level TBMChans using unsafePerformIO, because -- using atomically inside unsafePerformIO isn't possible. newTBMChanIO :: Int -> IO (TBMChan a) -- | Read the next value from the TBMChan, retrying if the channel -- is empty (and not closed). We return Nothing immediately if -- the channel is closed and empty. readTBMChan :: TBMChan a -> STM (Maybe a) -- | A version of readTBMChan which does not retry. Instead it -- returns Just Nothing if the channel is open but no value is -- available; it still returns Nothing if the channel is closed -- and empty. tryReadTBMChan :: TBMChan a -> STM (Maybe (Maybe a)) -- | Get the next value from the TBMChan without removing it, -- retrying if the channel is empty. peekTBMChan :: TBMChan a -> STM (Maybe a) -- | A version of peekTBMChan which does not retry. Instead it -- returns Just Nothing if the channel is open but no value is -- available; it still returns Nothing if the channel is closed -- and empty. tryPeekTBMChan :: TBMChan a -> STM (Maybe (Maybe a)) -- | Write a value to a TBMChan, retrying if the channel is full. -- If the channel is closed then the value is silently discarded. Use -- isClosedTBMChan to determine if the channel is closed before -- writing, as needed. writeTBMChan :: TBMChan a -> a -> STM () -- | A version of writeTBMChan which does not retry. Returns -- Just True if the value was successfully written, Just -- False if it could not be written (but the channel was open), and -- Nothing if it was discarded (i.e., the channel was closed). tryWriteTBMChan :: TBMChan a -> a -> STM (Maybe Bool) -- | Put a data item back onto a channel, where it will be the next item -- read. If the channel is closed then the value is silently discarded; -- you can use peekTBMChan to circumvent this in certain -- circumstances. N.B., this could allow the channel to -- temporarily become longer than the specified limit, which is necessary -- to ensure that the item is indeed the next one read. unGetTBMChan :: TBMChan a -> a -> STM () -- | Closes the TBMChan, preventing any further writes. closeTBMChan :: TBMChan a -> STM () -- | Returns True if the supplied TBMChan has been -- closed. isClosedTBMChan :: TBMChan a -> STM Bool -- | Returns True if the supplied TBMChan is empty (i.e., -- has no elements). N.B., a TBMChan can be both "empty" -- and "full" at the same time, if the initial limit was non-positive. isEmptyTBMChan :: TBMChan a -> STM Bool -- | Returns True if the supplied TBMChan is full (i.e., -- is over its limit). N.B., a TBMChan can be both -- "empty" and "full" at the same time, if the initial limit was -- non-positive. N.B., a TBMChan may still be full after -- reading, if unGetTBMChan was used to go over the initial limit. -- -- This is equivalent to: liftM (<= 0) -- estimateFreeSlotsTBMChan isFullTBMChan :: TBMChan a -> STM Bool -- | Estimate the number of free slots. If the result is positive, then -- it's a minimum bound; if it's non-positive then it's exact. It will -- only be negative if the initial limit was negative or if -- unGetTBMChan was used to go over the initial limit. -- -- This function always contends with writers, but only contends with -- readers when it has to; compare against freeSlotsTBMChan. estimateFreeSlotsTBMChan :: TBMChan a -> STM Int -- | Return the exact number of free slots. The result can be negative if -- the initial limit was negative or if unGetTBMChan was used to -- go over the initial limit. -- -- This function always contends with both readers and writers; compare -- against estimateFreeSlotsTBMChan. freeSlotsTBMChan :: TBMChan a -> STM Int -- | Build and returns a new instance of TBMQueue with the given -- capacity. N.B., we do not verify the capacity is positive, but -- if it is non-positive then writeTBMQueue will always retry and -- isFullTBMQueue will always be true. newTBMQueue :: Int -> STM (TBMQueue a) -- | IO version of newTBMQueue. This is useful for creating -- top-level TBMQueues using unsafePerformIO, because -- using atomically inside unsafePerformIO isn't possible. newTBMQueueIO :: Int -> IO (TBMQueue a) -- | Read the next value from the TBMQueue, retrying if the queue -- is empty (and not closed). We return Nothing immediately if -- the queue is closed and empty. readTBMQueue :: TBMQueue a -> STM (Maybe a) -- | A version of readTBMQueue which does not retry. Instead it -- returns Just Nothing if the queue is open but no value is -- available; it still returns Nothing if the queue is closed -- and empty. tryReadTBMQueue :: TBMQueue a -> STM (Maybe (Maybe a)) -- | Get the next value from the TBMQueue without removing it, -- retrying if the queue is empty. peekTBMQueue :: TBMQueue a -> STM (Maybe a) -- | A version of peekTBMQueue which does not retry. Instead it -- returns Just Nothing if the queue is open but no value is -- available; it still returns Nothing if the queue is closed -- and empty. tryPeekTBMQueue :: TBMQueue a -> STM (Maybe (Maybe a)) -- | Write a value to a TBMQueue, retrying if the queue is full. -- If the queue is closed then the value is silently discarded. Use -- isClosedTBMQueue to determine if the queue is closed before -- writing, as needed. writeTBMQueue :: TBMQueue a -> a -> STM () -- | A version of writeTBMQueue which does not retry. Returns -- Just True if the value was successfully written, Just -- False if it could not be written (but the queue was open), and -- Nothing if it was discarded (i.e., the queue was closed). tryWriteTBMQueue :: TBMQueue a -> a -> STM (Maybe Bool) -- | Put a data item back onto a queue, where it will be the next item -- read. If the queue is closed then the value is silently discarded; you -- can use peekTBMQueue to circumvent this in certain -- circumstances. N.B., this could allow the queue to temporarily -- become longer than the specified limit, which is necessary to ensure -- that the item is indeed the next one read. unGetTBMQueue :: TBMQueue a -> a -> STM () -- | Closes the TBMQueue, preventing any further writes. closeTBMQueue :: TBMQueue a -> STM () -- | Returns True if the supplied TBMQueue has been -- closed. isClosedTBMQueue :: TBMQueue a -> STM Bool -- | Returns True if the supplied TBMQueue is empty -- (i.e., has no elements). N.B., a TBMQueue can be both -- "empty" and "full" at the same time, if the initial limit was -- non-positive. isEmptyTBMQueue :: TBMQueue a -> STM Bool -- | Returns True if the supplied TBMQueue is full (i.e., -- is over its limit). N.B., a TBMQueue can be both -- "empty" and "full" at the same time, if the initial limit was -- non-positive. N.B., a TBMQueue may still be full after -- reading, if unGetTBMQueue was used to go over the initial -- limit. -- -- This is equivalent to: liftM (<= 0) -- estimateFreeSlotsTBMQueue isFullTBMQueue :: TBMQueue a -> STM Bool -- | Estimate the number of free slots. If the result is positive, then -- it's a minimum bound; if it's non-positive then it's exact. It will -- only be negative if the initial limit was negative or if -- unGetTBMQueue was used to go over the initial limit. -- -- This function always contends with writers, but only contends with -- readers when it has to; compare against freeSlotsTBMQueue. estimateFreeSlotsTBMQueue :: TBMQueue a -> STM Int -- | Return the exact number of free slots. The result can be negative if -- the initial limit was negative or if unGetTBMQueue was used to -- go over the initial limit. -- -- This function always contends with both readers and writers; compare -- against estimateFreeSlotsTBMQueue. freeSlotsTBMQueue :: TBMQueue a -> STM Int -- | Build and returns a new instance of TMChan. newTMChan :: STM (TMChan a) -- | IO version of newTMChan. This is useful for creating -- top-level TMChans using unsafePerformIO, because using -- atomically inside unsafePerformIO isn't possible. newTMChanIO :: IO (TMChan a) -- | Like newBroadcastTChan. -- -- Since: 2.1.0 newBroadcastTMChan :: STM (TMChan a) -- | IO version of newBroadcastTMChan. -- -- Since: 2.1.0 newBroadcastTMChanIO :: IO (TMChan a) -- | Duplicate a TMChan: the duplicate channel begins empty, but -- data written to either channel from then on will be available from -- both, and closing one copy will close them all. Hence this creates a -- kind of broadcast channel, where data written by anyone is seen by -- everyone else. dupTMChan :: TMChan a -> STM (TMChan a) -- | Read the next value from the TMChan, retrying if the channel -- is empty (and not closed). We return Nothing immediately if -- the channel is closed and empty. readTMChan :: TMChan a -> STM (Maybe a) -- | A version of readTMChan which does not retry. Instead it -- returns Just Nothing if the channel is open but no value is -- available; it still returns Nothing if the channel is closed -- and empty. tryReadTMChan :: TMChan a -> STM (Maybe (Maybe a)) -- | Get the next value from the TMChan without removing it, -- retrying if the channel is empty. peekTMChan :: TMChan a -> STM (Maybe a) -- | A version of peekTMChan which does not retry. Instead it -- returns Just Nothing if the channel is open but no value is -- available; it still returns Nothing if the channel is closed -- and empty. tryPeekTMChan :: TMChan a -> STM (Maybe (Maybe a)) -- | Write a value to a TMChan. If the channel is closed then the -- value is silently discarded. Use isClosedTMChan to determine if -- the channel is closed before writing, as needed. writeTMChan :: TMChan a -> a -> STM () -- | Put a data item back onto a channel, where it will be the next item -- read. If the channel is closed then the value is silently discarded; -- you can use peekTMChan to circumvent this in certain -- circumstances. unGetTMChan :: TMChan a -> a -> STM () -- | Closes the TMChan, preventing any further writes. closeTMChan :: TMChan a -> STM () -- | Returns True if the supplied TMChan has been closed. isClosedTMChan :: TMChan a -> STM Bool -- | Returns True if the supplied TMChan is empty. isEmptyTMChan :: TMChan a -> STM Bool -- | Build and returns a new instance of TMQueue. newTMQueue :: STM (TMQueue a) -- | IO version of newTMQueue. This is useful for creating -- top-level TMQueues using unsafePerformIO, because -- using atomically inside unsafePerformIO isn't possible. newTMQueueIO :: IO (TMQueue a) -- | Read the next value from the TMQueue, retrying if the queue -- is empty (and not closed). We return Nothing immediately if -- the queue is closed and empty. readTMQueue :: TMQueue a -> STM (Maybe a) -- | A version of readTMQueue which does not retry. Instead it -- returns Just Nothing if the queue is open but no value is -- available; it still returns Nothing if the queue is closed -- and empty. tryReadTMQueue :: TMQueue a -> STM (Maybe (Maybe a)) -- | Get the next value from the TMQueue without removing it, -- retrying if the queue is empty. peekTMQueue :: TMQueue a -> STM (Maybe a) -- | A version of peekTMQueue which does not retry. Instead it -- returns Just Nothing if the queue is open but no value is -- available; it still returns Nothing if the queue is closed -- and empty. tryPeekTMQueue :: TMQueue a -> STM (Maybe (Maybe a)) -- | Write a value to a TMQueue. If the queue is closed then the -- value is silently discarded. Use isClosedTMQueue to determine -- if the queue is closed before writing, as needed. writeTMQueue :: TMQueue a -> a -> STM () -- | Put a data item back onto a queue, where it will be the next item -- read. If the queue is closed then the value is silently discarded; you -- can use peekTMQueue to circumvent this in certain -- circumstances. unGetTMQueue :: TMQueue a -> a -> STM () -- | Closes the TMQueue, preventing any further writes. closeTMQueue :: TMQueue a -> STM () -- | Returns True if the supplied TMQueue has been -- closed. isClosedTMQueue :: TMQueue a -> STM Bool -- | Returns True if the supplied TMQueue is empty. isEmptyTMQueue :: TMQueue a -> STM Bool -- | Create a new MutVar with the specified initial value. newMutVar :: PrimMonad m => a -> m (MutVar (PrimState m) a) -- | Read the value of a MutVar. readMutVar :: PrimMonad m => MutVar (PrimState m) a -> m a -- | Write a new value into a MutVar. writeMutVar :: PrimMonad m => MutVar (PrimState m) a -> a -> m () -- | Atomically mutate the contents of a MutVar. -- -- This function is useful for using MutVar in a safe way in a -- multithreaded program. If you only have one MutVar, then using -- atomicModifyMutVar to access and modify it will prevent race -- conditions. -- -- Extending the atomicity to multiple MutVars is problematic, so -- if you need to do anything more complicated, using MVar instead -- is a good idea. -- -- atomicModifyMutVar does not apply the function strictly. This -- means if a program calls atomicModifyMutVar many times, but -- seldom uses the value, thunks will pile up in memory resulting in a -- space leak. To avoid this problem, use atomicModifyMutVar' -- instead. atomicModifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> (a, b)) -> m b -- | Strict version of atomicModifyMutVar. This forces both the -- value stored in the MutVar as well as the value returned. atomicModifyMutVar' :: PrimMonad m => MutVar (PrimState m) a -> (a -> (a, b)) -> m b -- | Mutate the contents of a MutVar. -- -- modifyMutVar does not apply the function strictly. This means -- if a program calls modifyMutVar many times, but seldom uses the -- value, thunks will pile up in memory resulting in a space leak. To -- avoid this problem, use modifyMutVar' instead. modifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m () -- | Strict version of modifyMutVar. modifyMutVar' :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m () -- | replaceElem old new replaces all old elements -- with new. replaceElem :: (MonoFunctor mono, Eq (Element mono)) => Element mono -> Element mono -> mono -> mono replaceElemStrictText :: Char -> Char -> Text -> Text replaceElemLazyText :: Char -> Char -> Text -> Text -- | Safe version of headEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. headMay :: MonoFoldable mono => mono -> Maybe (Element mono) -- | Safe version of lastEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. lastMay :: MonoFoldable mono => mono -> Maybe (Element mono) -- | osum computes the sum of the numbers of a monomorphic -- container. osum :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono -- | oproduct computes the product of the numbers of a monomorphic -- container. oproduct :: (MonoFoldable mono, Num (Element mono)) => mono -> Element mono -- | Are all of the elements True? oand :: (Element mono ~ Bool, MonoFoldable mono) => mono -> Bool -- | Are any of the elements True? oor :: (Element mono ~ Bool, MonoFoldable mono) => mono -> Bool -- | Synonym for ofoldMap oconcatMap :: (MonoFoldable mono, Monoid m) => (Element mono -> m) -> mono -> m -- | Monoidally combine all values in the container ofold :: (MonoFoldable mono, Monoid (Element mono)) => mono -> Element mono -- | Synonym for ofold oconcat :: (MonoFoldable mono, Monoid (Element mono)) => mono -> Element mono -- | Synonym for ofoldlM ofoldM :: (MonoFoldable mono, Monad m) => (a -> Element mono -> m a) -> a -> mono -> m a -- | Perform all actions in the given container osequence_ :: (Applicative m, MonoFoldable mono, Element mono ~ m ()) => mono -> m () -- | Get the minimum element of a monomorphic container. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See maximum from Data.NonNull for a total version of -- this function. maximumEx :: (MonoFoldable mono, Ord (Element mono)) => mono -> Element mono -- | Get the maximum element of a monomorphic container. -- -- Note: this is a partial function. On an empty MonoFoldable, it -- will throw an exception. -- -- See minimum from Data.NonNull for a total version of -- this function. minimumEx :: (MonoFoldable mono, Ord (Element mono)) => mono -> Element mono -- | Safe version of maximumEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. maximumMay :: (MonoFoldable mono, Ord (Element mono)) => mono -> Maybe (Element mono) -- | Safe version of maximumByEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. maximumByMay :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> mono -> Maybe (Element mono) -- | Safe version of minimumEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. minimumMay :: (MonoFoldable mono, Ord (Element mono)) => mono -> Maybe (Element mono) -- | Safe version of minimumByEx. -- -- Returns Nothing instead of throwing an exception when -- encountering an empty monomorphic container. minimumByMay :: MonoFoldable mono => (Element mono -> Element mono -> Ordering) -> mono -> Maybe (Element mono) -- | ofor is otraverse with its arguments flipped. ofor :: (MonoTraversable mono, Applicative f) => mono -> (Element mono -> f (Element mono)) -> f mono -- | oforM is omapM with its arguments flipped. oforM :: (MonoTraversable mono, Applicative f) => mono -> (Element mono -> f (Element mono)) -> f mono -- | A strict left fold, together with an unwrap function. -- -- This is convenient when the accumulator value is not the same as the -- final expected type. It is provided mainly for integration with the -- foldl package, to be used in conjunction with -- purely. ofoldlUnwrap :: MonoFoldable mono => (x -> Element mono -> x) -> x -> (x -> b) -> mono -> b -- | A monadic strict left fold, together with an unwrap function. -- -- Similar to foldlUnwrap, but allows monadic actions. To be -- used with impurely from foldl. ofoldMUnwrap :: (Monad m, MonoFoldable mono) => (x -> Element mono -> m x) -> m x -> (x -> m b) -> mono -> m b -- | intercalate seq seqs inserts seq in between -- seqs and concatenates the result. ointercalate :: (MonoFoldable mono, Monoid (Element mono)) => Element mono -> mono -> Element mono -- | Unwraps a WrappedMono. unwrapMono :: WrappedMono mono a -> mono -- | Synonym for olength64 length64 :: MonoFoldable mono => mono -> Int64 -- | Synonym for ofoldMap1Ex foldMap1Ex :: (MonoFoldable mono, Semigroup m) => (Element mono -> m) -> mono -> m -- | Synonym for ofoldr1Ex foldr1Ex :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> mono -> Element mono -- | Synonym for ofoldl1Ex' foldl1Ex' :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> mono -> Element mono -- | Synonym for opoint point :: MonoPointed mono => Element mono -> mono -- | Use Data.List's implementation of find. defaultFind :: MonoFoldable seq => (Element seq -> Bool) -> seq -> Maybe (Element seq) -- | Use Data.List's implementation of intersperse. defaultIntersperse :: IsSequence seq => Element seq -> seq -> seq -- | Use Data.List's implementation of reverse. defaultReverse :: IsSequence seq => seq -> seq -- | Use Data.List's implementation of sortBy. defaultSortBy :: IsSequence seq => (Element seq -> Element seq -> Ordering) -> seq -> seq -- | Use splitWhen from Data.List.Split defaultSplitWhen :: IsSequence seq => (Element seq -> Bool) -> seq -> [seq] -- | Sort a vector using an supplied element ordering function. vectorSortBy :: Vector v e => (e -> e -> Ordering) -> v e -> v e -- | Sort a vector. vectorSort :: (Vector v e, Ord e) => v e -> v e -- | Use Data.List's : to prepend an element to a sequence. defaultCons :: IsSequence seq => Element seq -> seq -> seq -- | Use Data.List's ++ to append an element to a sequence. defaultSnoc :: IsSequence seq => seq -> Element seq -> seq -- | like Data.List.tail, but an input of mempty returns -- mempty tailDef :: IsSequence seq => seq -> seq -- | like Data.List.init, but an input of mempty returns -- mempty initDef :: IsSequence seq => seq -> seq -- | splitElem splits a sequence into components delimited -- by separator element. It's equivalent to splitWhen with -- equality predicate: -- --
--   splitElem sep === splitWhen (== sep)
--   
-- -- Since 0.9.3 splitElem :: (IsSequence seq, Eq (Element seq)) => Element seq -> seq -> [seq] -- | splitSeq splits a sequence into components delimited -- by separator subsequence. splitSeq is the right inverse of -- intercalate: -- --
--   ointercalate x . splitSeq x === id
--   
-- -- splitElem can be considered a special case of splitSeq -- --
--   splitSeq (singleton sep) === splitElem sep
--   
-- -- splitSeq mempty is another special case: it splits -- just before each element, and in line with splitWhen rules, it -- has at least one output component: -- --
--   > splitSeq "" ""
--   [""]
--   > splitSeq "" "a"
--   ["", "a"]
--   > splitSeq "" "ab"
--   ["", "a", "b"]
--   
-- -- Since 0.9.3 splitSeq :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> [seq] -- | replaceSeq old new replaces all old -- subsequences with new. -- --
--   replaceSeq old new === ointercalate new . splitSeq old
--   
replaceSeq :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> seq -> seq -- | dropPrefix drops the given prefix from a sequence. It returns -- the original sequence if the sequence doesn't start with the given -- prefix. -- --
--   > dropPrefix "foo" "foobar"
--   "bar"
--   > dropPrefix "abc" "foobar"
--   "foobar"
--   
dropPrefix :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> seq -- | dropSuffix drops the given suffix from a sequence. It returns -- the original sequence if the sequence doesn't end with the given -- suffix. -- --
--   > dropSuffix "bar" "foobar"
--   "foo"
--   > dropSuffix "abc" "foobar"
--   "foobar"
--   
dropSuffix :: (IsSequence seq, Eq (Element seq)) => seq -> seq -> seq -- | ensurePrefix will add a prefix to a sequence if it doesn't -- exist, and otherwise have no effect. -- --
--   > ensurePrefix "foo" "foobar"
--   "foobar"
--   > ensurePrefix "abc" "foobar"
--   "abcfoobar"
--   
ensurePrefix :: (Eq (Element seq), IsSequence seq) => seq -> seq -> seq -- | Append a suffix to a sequence, unless it already has that suffix. -- --
--   > ensureSuffix "bar" "foobar"
--   "foobar"
--   > ensureSuffix "abc" "foobar"
--   "foobarabc"
--   
ensureSuffix :: (Eq (Element seq), IsSequence seq) => seq -> seq -> seq -- | Similar to standard group, but operates on the whole -- collection, not just the consecutive items. -- -- Equivalent to groupAllOn id groupAll :: (IsSequence seq, Eq (Element seq)) => seq -> [seq] splitElemStrictBS :: Word8 -> ByteString -> [ByteString] stripPrefixStrictBS :: ByteString -> ByteString -> Maybe ByteString stripSuffixStrictBS :: ByteString -> ByteString -> Maybe ByteString splitSeqLazyBS :: Word8 -> ByteString -> [ByteString] stripPrefixLazyBS :: ByteString -> ByteString -> Maybe ByteString stripSuffixLazyBS :: ByteString -> ByteString -> Maybe ByteString splitSeqStrictText :: Text -> Text -> [Text] replaceSeqStrictText :: Text -> Text -> Text -> Text splitSeqLazyText :: Text -> Text -> [Text] replaceSeqLazyText :: Text -> Text -> Text -> Text -- | Repack from one type to another, dropping to a list in the middle. -- -- repack = pack . unpack. repack :: (MonoFoldable a, IsSequence b, Element a ~ Element b) => a -> b -- | Safely convert from a NonEmpty list to a non-null -- monomorphic container. fromNonEmpty :: IsSequence seq => NonEmpty (Element seq) -> NonNull seq -- | Map each element of a monomorphic container to a semigroup, and -- combine the results. -- -- Safe version of ofoldMap1Ex, only works on monomorphic -- containers wrapped in a NonNull. -- --

Examples

-- --
--   > let xs = ncons ("hello", 1 :: Integer) [(" world", 2)]
--   > ofoldMap1 fst xs
--   "hello world"
--   
ofoldMap1 :: (MonoFoldable mono, Semigroup m) => (Element mono -> m) -> NonNull mono -> m -- | Right-associative fold of a monomorphic container with no base -- element. -- -- Safe version of ofoldr1Ex, only works on monomorphic containers -- wrapped in a NonNull. -- --
--   foldr1 f = Prelude.foldr1 f . otoList
--   
-- --

Examples

-- --
--   > let xs = ncons "a" ["b", "c"]
--   > ofoldr1 (++) xs
--   "abc"
--   
ofoldr1 :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> NonNull mono -> Element mono -- | Strict left-associative fold of a monomorphic container with no base -- element. -- -- Safe version of ofoldl1Ex', only works on monomorphic -- containers wrapped in a NonNull. -- --
--   foldl1' f = Prelude.foldl1' f . otoList
--   
-- --

Examples

-- --
--   > let xs = ncons "a" ["b", "c"]
--   > ofoldl1' (++) xs
--   "abc"
--   
ofoldl1' :: MonoFoldable mono => (Element mono -> Element mono -> Element mono) -> NonNull mono -> Element mono -- | Safely convert from an unsafe monomorphic container to a -- safe non-null monomorphic container. fromNullable :: MonoFoldable mono => mono -> Maybe (NonNull mono) -- | Unsafely convert from an unsafe monomorphic container to -- a safe non-null monomorphic container. -- -- Throws an exception if the monomorphic container is empty. impureNonNull :: MonoFoldable mono => mono -> NonNull mono -- | Old synonym for impureNonNull nonNull :: MonoFoldable mono => mono -> NonNull mono -- | Specializes fromNonEmpty to lists only. toMinList :: NonEmpty a -> NonNull [a] -- | Prepend an element to a SemiSequence, creating a non-null -- SemiSequence. -- -- Generally this uses cons underneath. cons is not efficient for most -- data structures. -- -- Alternatives: -- -- ncons :: SemiSequence seq => Element seq -> seq -> NonNull seq -- | Extract the first element of a sequnce and the rest of the non-null -- sequence if it exists. nuncons :: IsSequence seq => NonNull seq -> (Element seq, Maybe (NonNull seq)) -- | Same as nuncons with no guarantee that the rest of the sequence -- is non-null. splitFirst :: IsSequence seq => NonNull seq -> (Element seq, seq) -- | Equivalent to Data.Sequences.filter, but works -- on non-nullable sequences. nfilter :: IsSequence seq => (Element seq -> Bool) -> NonNull seq -> seq -- | Equivalent to Data.Sequences.filterM, but works -- on non-nullable sequences. nfilterM :: (Monad m, IsSequence seq) => (Element seq -> m Bool) -> NonNull seq -> m seq -- | Equivalent to Data.Sequences.replicate -- -- i must be > 0 -- -- i <= 0 is treated the same as providing 1 nReplicate :: IsSequence seq => Index seq -> Element seq -> NonNull seq -- | Join a monomorphic container, whose elements are Semigroups, -- together. -- -- Safe, only works on monomorphic containers wrapped in a -- NonNull. -- --

Examples

-- --
--   > let xs = ncons "a" ["b", "c"]
--   > xs
--   NonNull {toNullable = ["a","b","c"]}
--   
--   > ofold1 xs
--   "abc"
--   
ofold1 :: (MonoFoldable mono, Semigroup (Element mono)) => NonNull mono -> Element mono -- | fmap over the underlying container in a NonNull. mapNonNull :: (Functor f, MonoFoldable (f b)) => (a -> b) -> NonNull (f a) -> NonNull (f b) -- | Same as say, but operates on a String. Note that this -- will force the entire String into memory at once, and will -- fail for infinite Strings. sayString :: MonadIO m => String -> m () -- | Same as say, but for instances of Show. -- -- If your Show instance generates infinite output, this will -- fail. However, an infinite result for show would generally be -- considered an invalid instance anyway. sayShow :: (MonadIO m, Show a) => a -> m () -- | Same as say, but data is sent to standard error. sayErr :: MonadIO m => Text -> m () -- | Same as sayString, but data is sent to standard error. sayErrString :: MonadIO m => String -> m () -- | Same as sayShow, but data is sent to standard error. sayErrShow :: (MonadIO m, Show a) => a -> m () -- | Same as say, but data is sent to the provided Handle. hSay :: MonadIO m => Handle -> Text -> m () -- | Same as sayString, but data is sent to the provided -- Handle. hSayString :: MonadIO m => Handle -> String -> m () -- | Same as sayShow, but data is sent to the provided -- Handle. hSayShow :: (MonadIO m, Show a) => Handle -> a -> m () -- | Create an Acquire value using the given allocate and free -- functions. -- -- To acquire and free the resource in an arbitrary monad with -- MonadUnliftIO, do the following: -- --
--   acquire <- withRunInIO $ \runInIO ->
--     return $ mkAcquire (runInIO create) (runInIO . free)
--   
-- -- Note that this is only safe if the Acquire is run and freed within the -- same monadic scope it was created in. mkAcquire :: IO a -> (a -> IO ()) -> Acquire a -- | Same as mkAcquire, but the cleanup function will be informed of -- how cleanup was initiated. This allows you to distinguish, for -- example, between normal and exceptional exits. -- -- To acquire and free the resource in an arbitrary monad with -- MonadUnliftIO, do the following: -- --
--   acquire <- withRunInIO $ \runInIO ->
--     return $ mkAcquireType (runInIO create) (\a -> runInIO . free a)
--   
-- -- Note that this is only safe if the Acquire is run and freed within the -- same monadic scope it was created in. mkAcquireType :: IO a -> (a -> ReleaseType -> IO ()) -> Acquire a -- | Allocate a resource and register an action with the -- MonadResource to free the resource. allocateAcquire :: MonadResource m => Acquire a -> m (ReleaseKey, a) -- | Longer name for with, in case with is not obvious -- enough in context. withAcquire :: MonadUnliftIO m => Acquire a -> (a -> m b) -> m b -- | Unwrap a ResourceT transformer, and call all registered release -- actions. -- -- Note that there is some reference counting involved due to -- resourceForkIO. If multiple threads are sharing the same -- collection of resources, only the last call to runResourceT -- will deallocate the resources. -- -- NOTE Since version 1.2.0, this function will throw a -- ResourceCleanupException if any of the cleanup functions throw -- an exception. runResourceT :: MonadUnliftIO m => ResourceT m a -> m a sealConduitT :: forall i o (m :: Type -> Type) r. ConduitT i o m r -> SealedConduitT i o m r unsealConduitT :: forall (m :: Type -> Type) i o r. Monad m => SealedConduitT i o m r -> ConduitT i o m r -- | Generalize a Source to a Producer. -- -- Since 1.0.0 toProducer :: forall (m :: Type -> Type) a i. Monad m => ConduitT () a m () -> ConduitT i a m () -- | Generalize a Sink to a Consumer. -- -- Since 1.0.0 toConsumer :: forall (m :: Type -> Type) a b o. Monad m => ConduitT a Void m b -> ConduitT a o m b -- | Catch all exceptions thrown by the current component of the pipeline. -- -- Note: this will not catch exceptions thrown by other -- components! For example, if an exception is thrown in a -- Source feeding to a Sink, and the Sink uses -- catchC, the exception will not be caught. -- -- Due to this behavior (as well as lack of async exception safety), you -- should not try to implement combinators such as onException -- in terms of this primitive function. -- -- Note also that the exception handling will not be applied to -- any finalizers generated by this conduit. -- -- Since 1.0.11 catchC :: forall (m :: Type -> Type) e i o r. (MonadUnliftIO m, Exception e) => ConduitT i o m r -> (e -> ConduitT i o m r) -> ConduitT i o m r -- | The same as flip catchC. -- -- Since 1.0.11 handleC :: forall (m :: Type -> Type) e i o r. (MonadUnliftIO m, Exception e) => (e -> ConduitT i o m r) -> ConduitT i o m r -> ConduitT i o m r -- | A version of try for use within a pipeline. See the comments -- in catchC for more details. -- -- Since 1.0.11 tryC :: forall (m :: Type -> Type) e i o r. (MonadUnliftIO m, Exception e) => ConduitT i o m r -> ConduitT i o m (Either e r) -- | Same as normal fusion (e.g. =$=), except instead of -- discarding leftovers from the downstream component, return them. -- -- Since 1.0.17 fuseReturnLeftovers :: forall (m :: Type -> Type) a b c r. Monad m => ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m (r, [b]) -- | Similar to fuseReturnLeftovers, but use the provided function -- to convert downstream leftovers to upstream leftovers. -- -- Since 1.0.17 fuseLeftovers :: forall (m :: Type -> Type) b a c r. Monad m => ([b] -> [a]) -> ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r -- | Merge a Source into a Conduit. The new conduit will -- stop processing once either source or upstream have been exhausted. mergeSource :: forall (m :: Type -> Type) i a. Monad m => ConduitT () i m () -> ConduitT a (i, a) m () -- | Turn a Sink into a Conduit in the following way: -- -- -- -- Note that the Sink will stop receiving input as soon as the -- downstream it is connected to shuts down. -- -- An example usage would be to write the result of a Sink to -- some mutable variable while allowing other processing to continue. -- -- Since 1.1.0 passthroughSink :: Monad m => ConduitT i Void m r -> (r -> m ()) -> ConduitT i i m () -- | Convert a Source into a list. The basic functionality can be -- explained as: -- --
--   sourceToList src = src $$ Data.Conduit.List.consume
--   
-- -- However, sourceToList is able to produce its results lazily, -- which cannot be done when running a conduit pipeline in general. -- Unlike the Data.Conduit.Lazy module (in conduit-extra), this -- function performs no unsafe I/O operations, and therefore can only be -- as lazy as the underlying monad. -- -- Since 1.2.6 sourceToList :: Monad m => ConduitT () a m () -> m [a] -- | Equivalent to using runConduit and .| together. -- -- Since 1.2.3 connect :: Monad m => ConduitT () a m () -> ConduitT a Void m r -> m r -- | Named function synonym for .| -- -- Equivalent to .| and =$=. However, the latter is -- deprecated and will be removed in a future version. -- -- Since 1.2.3 fuse :: forall (m :: Type -> Type) a b c r. Monad m => ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r -- | Combine two Conduits together into a new Conduit -- (aka fuse). -- -- Output from the upstream (left) conduit will be fed into the -- downstream (right) conduit. Processing will terminate when downstream -- (right) returns. Leftover data returned from the right -- Conduit will be discarded. -- -- Equivalent to fuse and =$=, however the latter is -- deprecated and will be removed in a future version. -- -- Note that, while this operator looks like categorical composition -- (from Control.Category), there are a few reasons it's -- different: -- -- (.|) :: forall (m :: Type -> Type) a b c r. Monad m => ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r infixr 2 .| -- | The connect operator, which pulls data from a source and pushes to a -- sink. If you would like to keep the Source open to be used -- for other operations, use the connect-and-resume operator $$+. -- -- Since 0.4.0 ($$) :: Monad m => Source m a -> Sink a m b -> m b infixr 0 $$ -- | A synonym for =$= for backwards compatibility. -- -- Since 0.4.0 (=$) :: forall (m :: Type -> Type) a b c r. Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r infixr 2 =$ -- | Deprecated fusion operator. -- -- Since 0.4.0 (=$=) :: forall (m :: Type -> Type) a b c r. Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r infixr 2 =$= -- | Wait for a single input value from upstream. If no data is available, -- returns Nothing. Once await returns -- Nothing, subsequent calls will also return Nothing. -- -- Since 0.5.0 await :: forall (m :: Type -> Type) i o. Monad m => ConduitT i o m (Maybe i) -- | Send a monadic value downstream for the next component to consume. yieldM :: Monad m => m o -> ConduitT i o m () -- | Provide a single piece of leftover input to be consumed by the next -- component in the current monadic binding. -- -- Note: it is highly encouraged to only return leftover values -- from input already consumed from upstream. leftover :: forall i o (m :: Type -> Type). i -> ConduitT i o m () -- | Run a pipeline until processing completes. -- -- Since 1.2.1 runConduit :: Monad m => ConduitT () Void m r -> m r -- | Bracket a conduit computation between allocation and release of a -- resource. Two guarantees are given about resource finalization: -- --
    --
  1. It will be prompt. The finalization will be run as early as -- possible.
  2. --
  3. It is exception safe. Due to usage of resourcet, the -- finalization will be run in the event of any exceptions.
  4. --
-- -- Since 0.5.0 bracketP :: forall (m :: Type -> Type) a i o r. MonadResource m => IO a -> (a -> IO ()) -> (a -> ConduitT i o m r) -> ConduitT i o m r -- | Wait for input forever, calling the given inner component for each -- piece of new input. -- -- This function is provided as a convenience for the common pattern of -- awaiting input, checking if it's Just and then -- looping. -- -- Since 0.5.0 awaitForever :: forall (m :: Type -> Type) i o r. Monad m => (i -> ConduitT i o m r) -> ConduitT i o m () -- | Transform the monad that a ConduitT lives in. -- -- Note that the monad transforming function will be run multiple times, -- resulting in unintuitive behavior in some cases. For a fuller -- treatment, please see: -- -- -- https://github.com/snoyberg/conduit/wiki/Dealing-with-monad-transformers -- -- Since 0.4.0 transPipe :: Monad m => (forall a. () => m a -> n a) -> ConduitT i o m r -> ConduitT i o n r -- | Apply a function to all the output values of a ConduitT. -- -- This mimics the behavior of fmap for a Source and -- Conduit in pre-0.4 days. It can also be simulated by fusing -- with the map conduit from Data.Conduit.List. -- -- Since 0.4.1 mapOutput :: forall (m :: Type -> Type) o1 o2 i r. Monad m => (o1 -> o2) -> ConduitT i o1 m r -> ConduitT i o2 m r -- | Same as mapOutput, but use a function that returns -- Maybe values. -- -- Since 0.5.0 mapOutputMaybe :: forall (m :: Type -> Type) o1 o2 i r. Monad m => (o1 -> Maybe o2) -> ConduitT i o1 m r -> ConduitT i o2 m r -- | Apply a function to all the input values of a ConduitT. -- -- Since 0.5.0 mapInput :: forall (m :: Type -> Type) i1 i2 o r. Monad m => (i1 -> i2) -> (i2 -> Maybe i1) -> ConduitT i2 o m r -> ConduitT i1 o m r -- | Apply a monadic action to all the input values of a ConduitT. -- -- Since 1.3.2 mapInputM :: Monad m => (i1 -> m i2) -> (i2 -> m (Maybe i1)) -> ConduitT i2 o m r -> ConduitT i1 o m r -- | The connect-and-resume operator. This does not close the -- Source, but instead returns it to be used again. This allows -- a Source to be used incrementally in a large program, without -- forcing the entire program to live in the Sink monad. -- -- Mnemonic: connect + do more. -- -- Since 0.5.0 ($$+) :: Monad m => ConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b) infixr 0 $$+ -- | Continue processing after usage of $$+. -- -- Since 0.5.0 ($$++) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b) infixr 0 $$++ -- | Same as $$++ and connectResume, but doesn't include -- the updated SealedConduitT. -- -- NOTE In previous versions, this would cause finalizers to run. -- Since version 1.3.0, there are no finalizers in conduit. -- -- Since 0.5.0 ($$+-) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m b infixr 0 $$+- -- | Left fusion for a sealed source. -- -- Since 1.0.16 ($=+) :: forall (m :: Type -> Type) a b. Monad m => SealedConduitT () a m () -> ConduitT a b m () -> SealedConduitT () b m () infixl 1 $=+ -- | Coalesce all values yielded by all of the Sources. -- -- Implemented on top of ZipSource and as such, it exhibits the -- same short-circuiting behavior as ZipSource. See that data -- type for more details. If you want to create a source that yields -- *all* values from multiple sources, use sequence_. -- -- Since 1.0.13 sequenceSources :: forall f (m :: Type -> Type) o. (Traversable f, Monad m) => f (ConduitT () o m ()) -> ConduitT () (f o) m () -- | Send incoming values to all of the Sink providing, and -- ultimately coalesce together all return values. -- -- Implemented on top of ZipSink, see that data type for more -- details. -- -- Since 1.0.13 sequenceSinks :: forall f (m :: Type -> Type) i r. (Traversable f, Monad m) => f (ConduitT i Void m r) -> ConduitT i Void m (f r) -- | The connect-and-resume operator. This does not close the -- Conduit, but instead returns it to be used again. This allows -- a Conduit to be used incrementally in a large program, -- without forcing the entire program to live in the Sink monad. -- -- Leftover data returned from the Sink will be discarded. -- -- Mnemonic: connect + do more. -- -- Since 1.0.17 (=$$+) :: forall (m :: Type -> Type) a b r. Monad m => ConduitT a b m () -> ConduitT b Void m r -> ConduitT a Void m (SealedConduitT a b m (), r) infixr 0 =$$+ -- | Continue processing after usage of =$$+. Connect a -- SealedConduitT to a sink and return the output of the sink -- together with a new SealedConduitT. -- -- Since 1.0.17 (=$$++) :: forall (m :: Type -> Type) i o r. Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m (SealedConduitT i o m (), r) infixr 0 =$$++ -- | Same as =$$++, but doesn't include the updated -- SealedConduitT. -- -- NOTE In previous versions, this would cause finalizers to run. -- Since version 1.3.0, there are no finalizers in conduit. -- -- Since 1.0.17 (=$$+-) :: forall (m :: Type -> Type) i o r. Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m r infixr 0 =$$+- -- | Provide identical input to all of the Conduits and combine -- their outputs into a single stream. -- -- Implemented on top of ZipConduit, see that data type for more -- details. -- -- Since 1.0.17 sequenceConduits :: forall f (m :: Type -> Type) i o r. (Traversable f, Monad m) => f (ConduitT i o m r) -> ConduitT i o m (f r) -- | Fuse two ConduitTs together, and provide the return value of -- both. Note that this will force the entire upstream ConduitT -- to be run to produce the result value, even if the downstream -- terminates early. -- -- Since 1.1.5 fuseBoth :: forall (m :: Type -> Type) a b r1 c r2. Monad m => ConduitT a b m r1 -> ConduitT b c m r2 -> ConduitT a c m (r1, r2) -- | Like fuseBoth, but does not force consumption of the -- Producer. In the case that the Producer terminates, -- the result value is provided as a Just value. If it does not -- terminate, then a Nothing value is returned. -- -- One thing to note here is that "termination" here only occurs if the -- Producer actually yields a Nothing value. For -- example, with the Producer mapM_ yield [1..5], if -- five values are requested, the Producer has not yet -- terminated. Termination only occurs when the sixth value is awaited -- for and the Producer signals termination. -- -- Since 1.2.4 fuseBothMaybe :: forall (m :: Type -> Type) a b r1 c r2. Monad m => ConduitT a b m r1 -> ConduitT b c m r2 -> ConduitT a c m (Maybe r1, r2) -- | Same as fuseBoth, but ignore the return value from the -- downstream Conduit. Same caveats of forced consumption apply. -- -- Since 1.1.5 fuseUpstream :: forall (m :: Type -> Type) a b r c. Monad m => ConduitT a b m r -> ConduitT b c m () -> ConduitT a c m r -- | Run a pure pipeline until processing completes, i.e. a pipeline with -- Identity as the base monad. This is equivalient to -- runIdentity . runConduit. runConduitPure :: ConduitT () Void Identity r -> r -- | Run a pipeline which acquires resources with ResourceT, and -- then run the ResourceT transformer. This is equivalent to -- runResourceT . runConduit. runConduitRes :: MonadUnliftIO m => ConduitT () Void (ResourceT m) r -> m r -- | Wrap the base monad in ExceptT -- -- Since 1.2.12 exceptC :: forall (m :: Type -> Type) i o e a. Monad m => ConduitT i o m (Either e a) -> ConduitT i o (ExceptT e m) a -- | Run ExceptT in the base monad -- -- Since 1.2.12 runExceptC :: forall (m :: Type -> Type) i o e r. Monad m => ConduitT i o (ExceptT e m) r -> ConduitT i o m (Either e r) -- | Catch an error in the base monad -- -- Since 1.2.12 catchExceptC :: forall (m :: Type -> Type) i o e r. Monad m => ConduitT i o (ExceptT e m) r -> (e -> ConduitT i o (ExceptT e m) r) -> ConduitT i o (ExceptT e m) r -- | Run CatchT in the base monad -- -- Since 1.1.0 runCatchC :: forall (m :: Type -> Type) i o r. Monad m => ConduitT i o (CatchT m) r -> ConduitT i o m (Either SomeException r) -- | Catch an exception in the base monad -- -- Since 1.1.0 catchCatchC :: forall (m :: Type -> Type) i o r. Monad m => ConduitT i o (CatchT m) r -> (SomeException -> ConduitT i o (CatchT m) r) -> ConduitT i o (CatchT m) r -- | Wrap the base monad in MaybeT -- -- Since 1.0.11 maybeC :: forall (m :: Type -> Type) i o a. Monad m => ConduitT i o m (Maybe a) -> ConduitT i o (MaybeT m) a -- | Run MaybeT in the base monad -- -- Since 1.0.11 runMaybeC :: forall (m :: Type -> Type) i o r. Monad m => ConduitT i o (MaybeT m) r -> ConduitT i o m (Maybe r) -- | Wrap the base monad in ReaderT -- -- Since 1.0.11 readerC :: forall (m :: Type -> Type) r i o a. Monad m => (r -> ConduitT i o m a) -> ConduitT i o (ReaderT r m) a -- | Run ReaderT in the base monad -- -- Since 1.0.11 runReaderC :: forall (m :: Type -> Type) r i o res. Monad m => r -> ConduitT i o (ReaderT r m) res -> ConduitT i o m res -- | Wrap the base monad in StateT -- -- Since 1.0.11 stateLC :: forall (m :: Type -> Type) s i o a. Monad m => (s -> ConduitT i o m (a, s)) -> ConduitT i o (StateT s m) a -- | Run StateT in the base monad -- -- Since 1.0.11 runStateLC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m (r, s) -- | Evaluate StateT in the base monad -- -- Since 1.0.11 evalStateLC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m r -- | Execute StateT in the base monad -- -- Since 1.0.11 execStateLC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m s -- | Wrap the base monad in StateT -- -- Since 1.0.11 stateC :: forall (m :: Type -> Type) s i o a. Monad m => (s -> ConduitT i o m (a, s)) -> ConduitT i o (StateT s m) a -- | Run StateT in the base monad -- -- Since 1.0.11 runStateC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m (r, s) -- | Evaluate StateT in the base monad -- -- Since 1.0.11 evalStateC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m r -- | Execute StateT in the base monad -- -- Since 1.0.11 execStateC :: forall (m :: Type -> Type) s i o r. Monad m => s -> ConduitT i o (StateT s m) r -> ConduitT i o m s -- | Wrap the base monad in WriterT -- -- Since 1.0.11 writerLC :: forall (m :: Type -> Type) w i o b. (Monad m, Monoid w) => ConduitT i o m (b, w) -> ConduitT i o (WriterT w m) b -- | Run WriterT in the base monad -- -- Since 1.0.11 runWriterLC :: forall (m :: Type -> Type) w i o r. (Monad m, Monoid w) => ConduitT i o (WriterT w m) r -> ConduitT i o m (r, w) -- | Execute WriterT in the base monad -- -- Since 1.0.11 execWriterLC :: forall (m :: Type -> Type) w i o r. (Monad m, Monoid w) => ConduitT i o (WriterT w m) r -> ConduitT i o m w -- | Wrap the base monad in WriterT -- -- Since 1.0.11 writerC :: forall (m :: Type -> Type) w i o b. (Monad m, Monoid w) => ConduitT i o m (b, w) -> ConduitT i o (WriterT w m) b -- | Run WriterT in the base monad -- -- Since 1.0.11 runWriterC :: forall (m :: Type -> Type) w i o r. (Monad m, Monoid w) => ConduitT i o (WriterT w m) r -> ConduitT i o m (r, w) -- | Execute WriterT in the base monad -- -- Since 1.0.11 execWriterC :: forall (m :: Type -> Type) w i o r. (Monad m, Monoid w) => ConduitT i o (WriterT w m) r -> ConduitT i o m w -- | Wrap the base monad in RWST -- -- Since 1.0.11 rwsLC :: forall (m :: Type -> Type) w r s i o a. (Monad m, Monoid w) => (r -> s -> ConduitT i o m (a, s, w)) -> ConduitT i o (RWST r w s m) a -- | Run RWST in the base monad -- -- Since 1.0.11 runRWSLC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (res, s, w) -- | Evaluate RWST in the base monad -- -- Since 1.0.11 evalRWSLC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (res, w) -- | Execute RWST in the base monad -- -- Since 1.0.11 execRWSLC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (s, w) -- | Wrap the base monad in RWST -- -- Since 1.0.11 rwsC :: forall (m :: Type -> Type) w r s i o a. (Monad m, Monoid w) => (r -> s -> ConduitT i o m (a, s, w)) -> ConduitT i o (RWST r w s m) a -- | Run RWST in the base monad -- -- Since 1.0.11 runRWSC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (res, s, w) -- | Evaluate RWST in the base monad -- -- Since 1.0.11 evalRWSC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (res, w) -- | Execute RWST in the base monad -- -- Since 1.0.11 execRWSC :: forall (m :: Type -> Type) w r s i o res. (Monad m, Monoid w) => r -> s -> ConduitT i o (RWST r w s m) res -> ConduitT i o m (s, w) -- | Yield each of the values contained by the given MonoFoldable. -- -- This will work on many data structures, including lists, -- ByteStrings, and Vectors. -- -- Subject to fusion yieldMany :: forall (m :: Type -> Type) mono i. (Monad m, MonoFoldable mono) => mono -> ConduitT i (Element mono) m () -- | Generate a producer by yielding each of the strict chunks in a -- LazySequence. -- -- For more information, see toChunks. -- -- Subject to fusion sourceLazy :: forall (m :: Type -> Type) lazy strict i. (Monad m, LazySequence lazy strict) => lazy -> ConduitT i strict m () -- | Stream the contents of a Handle as binary data. Note that this -- function will not automatically close the Handle when -- processing completes, since it did not acquire the Handle in -- the first place. sourceHandle :: forall (m :: Type -> Type) i. MonadIO m => Handle -> ConduitT i ByteString m () -- | Same as sourceHandle, but instead of allocating a new buffer -- for each incoming chunk of data, reuses the same buffer. Therefore, -- the ByteStrings yielded by this function are not -- referentially transparent between two different yields. -- -- This function will be slightly more efficient than -- sourceHandle by avoiding allocations and reducing garbage -- collections, but should only be used if you can guarantee that you do -- not reuse a ByteString (or any slice thereof) between two -- calls to await. sourceHandleUnsafe :: forall (m :: Type -> Type) i. MonadIO m => Handle -> ConduitT i ByteString m () -- | An alternative to sourceHandle. Instead of taking a pre-opened -- Handle, it takes an action that opens a Handle (in read -- mode), so that it can open it only when needed and close it as soon as -- possible. sourceIOHandle :: forall (m :: Type -> Type) i. MonadResource m => IO Handle -> ConduitT i ByteString m () -- | Same as sourceFile. The alternate name is a holdover from an -- older version, when sourceFile was more polymorphic than it is -- today. sourceFileBS :: forall (m :: Type -> Type) i. MonadResource m => FilePath -> ConduitT i ByteString m () -- | Stream all incoming data to the given file. sinkFile :: forall (m :: Type -> Type) o. MonadResource m => FilePath -> ConduitT ByteString o m () -- | Cautious version of sinkFile. The idea here is to stream the -- values to a temporary file in the same directory of the destination -- file, and only on successfully writing the entire file, moves it -- atomically to the destination path. -- -- In the event of an exception occurring, the temporary file will be -- deleted and no move will be made. If the application shuts down -- without running exception handling (such as machine failure or a -- SIGKILL), the temporary file will remain and the destination file will -- be untouched. sinkFileCautious :: forall (m :: Type -> Type) o. MonadResource m => FilePath -> ConduitM ByteString o m () -- | Like sinkFileCautious, but uses the with pattern -- instead of MonadResource. withSinkFileCautious :: forall m (n :: Type -> Type) o a. (MonadUnliftIO m, MonadIO n) => FilePath -> (ConduitM ByteString o n () -> m a) -> m a -- | Stream data into a temporary file in the given directory with the -- given filename pattern, and return the temporary filename. The -- temporary file will be automatically deleted when exiting the active -- ResourceT block, if it still exists. sinkTempFile :: forall (m :: Type -> Type) o. MonadResource m => FilePath -> String -> ConduitM ByteString o m FilePath -- | Same as sinkTempFile, but will use the default temp file -- directory for the system as the first argument. sinkSystemTempFile :: forall (m :: Type -> Type) o. MonadResource m => String -> ConduitM ByteString o m FilePath -- | Stream all incoming data to the given Handle. Note that this -- function does not flush and will not close the -- Handle when processing completes. sinkHandle :: forall (m :: Type -> Type) o. MonadIO m => Handle -> ConduitT ByteString o m () -- | Stream incoming builders, executing them directly on the buffer of the -- given Handle. Note that this function does not -- automatically close the Handle when processing completes. -- Pass flush to flush the buffer. sinkHandleBuilder :: forall (m :: Type -> Type) o. MonadIO m => Handle -> ConduitM Builder o m () -- | Stream incoming Flushes, executing them on IO.Handle -- Note that this function does not automatically close the -- Handle when processing completes sinkHandleFlush :: forall (m :: Type -> Type) o. MonadIO m => Handle -> ConduitM (Flush ByteString) o m () -- | An alternative to sinkHandle. Instead of taking a pre-opened -- Handle, it takes an action that opens a Handle (in write -- mode), so that it can open it only when needed and close it as soon as -- possible. sinkIOHandle :: forall (m :: Type -> Type) o. MonadResource m => IO Handle -> ConduitT ByteString o m () -- | Like withBinaryFile, but provides a source to read bytes from. withSourceFile :: forall m (n :: Type -> Type) i a. (MonadUnliftIO m, MonadIO n) => FilePath -> (ConduitM i ByteString n () -> m a) -> m a -- | Like withBinaryFile, but provides a sink to write bytes to. withSinkFile :: forall m (n :: Type -> Type) o a. (MonadUnliftIO m, MonadIO n) => FilePath -> (ConduitM ByteString o n () -> m a) -> m a -- | Same as withSinkFile, but lets you use a Builder. withSinkFileBuilder :: forall m (n :: Type -> Type) o a. (MonadUnliftIO m, MonadIO n) => FilePath -> (ConduitM Builder o n () -> m a) -> m a -- | Stream the contents of the given directory, without traversing deeply. -- -- This function will return all of the contents of the directory, -- whether they be files, directories, etc. -- -- Note that the generated filepaths will be the complete path, not just -- the filename. In other words, if you have a directory foo -- containing files bar and baz, and you use -- sourceDirectory on foo, the results will be -- foo/bar and foo/baz. sourceDirectory :: forall (m :: Type -> Type) i. MonadResource m => FilePath -> ConduitT i FilePath m () -- | Deeply stream the contents of the given directory. -- -- This works the same as sourceDirectory, but will not return -- directories at all. This function also takes an extra parameter to -- indicate whether symlinks will be followed. sourceDirectoryDeep :: forall (m :: Type -> Type) i. MonadResource m => Bool -> FilePath -> ConduitT i FilePath m () -- | Consume all incoming strict chunks into a lazy sequence. Note that the -- entirety of the sequence will be resident at memory. -- -- This can be used to consume a stream of strict ByteStrings into a lazy -- ByteString, for example. -- -- Subject to fusion sinkLazy :: forall (m :: Type -> Type) lazy strict o. (Monad m, LazySequence lazy strict) => ConduitT strict o m lazy -- | Consume all values from the stream and return as a list. Note that -- this will pull all values into memory. -- -- Subject to fusion sinkList :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m [a] -- | Sink incoming values into a vector, growing the vector as necessary to -- fit more elements. -- -- Note that using this function is more memory efficient than -- sinkList and then converting to a Vector, as it -- avoids intermediate list constructors. -- -- Subject to fusion sinkVector :: forall v a (m :: Type -> Type) o. (Vector v a, PrimMonad m) => ConduitT a o m (v a) -- | Sink incoming values into a vector, up until size maxSize. -- Subsequent values will be left in the stream. If there are less than -- maxSize values present, returns a Vector of smaller -- size. -- -- Note that using this function is more memory efficient than -- sinkList and then converting to a Vector, as it -- avoids intermediate list constructors. -- -- Subject to fusion sinkVectorN :: forall v a (m :: Type -> Type) o. (Vector v a, PrimMonad m) => Int -> ConduitT a o m (v a) -- | Same as sinkBuilder, but afterwards convert the builder to -- its lazy representation. -- -- Alternatively, this could be considered an alternative to -- sinkLazy, with the following differences: -- -- -- -- Subject to fusion sinkLazyBuilder :: forall (m :: Type -> Type) o. Monad m => ConduitT Builder o m ByteString -- | Consume and discard all remaining values in the stream. -- -- Subject to fusion sinkNull :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m () -- | Same as await, but discards any leading onull values. awaitNonNull :: forall (m :: Type -> Type) a o. (Monad m, MonoFoldable a) => ConduitT a o m (Maybe (NonNull a)) -- | sinkFile specialized to ByteString to help with type -- inference. sinkFileBS :: forall (m :: Type -> Type) o. MonadResource m => FilePath -> ConduitT ByteString o m () -- | Incrementally execute builders and pass on the filled chunks as -- bytestrings. builderToByteString :: forall (m :: Type -> Type). PrimMonad m => ConduitT Builder ByteString m () -- | Same as builderToByteString, but input and output are wrapped -- in Flush. builderToByteStringFlush :: forall (m :: Type -> Type). PrimMonad m => ConduitT (Flush Builder) (Flush ByteString) m () -- | Incrementally execute builders on the given buffer and pass on the -- filled chunks as bytestrings. Note that, if the given buffer is too -- small for the execution of a build step, a larger one will be -- allocated. -- -- WARNING: This conduit yields bytestrings that are NOT referentially -- transparent. Their content will be overwritten as soon as control is -- returned from the inner sink! unsafeBuilderToByteString :: forall (m :: Type -> Type). PrimMonad m => ConduitT Builder ByteString m () -- | A conduit that incrementally executes builders and passes on the -- filled chunks as bytestrings to an inner sink. -- -- INV: All bytestrings passed to the inner sink are non-empty. builderToByteStringWith :: forall (m :: Type -> Type). PrimMonad m => BufferAllocStrategy -> ConduitT Builder ByteString m () builderToByteStringWithFlush :: forall (m :: Type -> Type). PrimMonad m => BufferAllocStrategy -> ConduitT (Flush Builder) (Flush ByteString) m () -- | The simplest buffer allocation strategy: whenever a buffer is -- requested, allocate a new one that is big enough for the next build -- step to execute. -- -- NOTE that this allocation strategy may spill quite some memory upon -- direct insertion of a bytestring by the builder. Thats no problem for -- garbage collection, but it may lead to unreasonably high memory -- consumption in special circumstances. allNewBuffersStrategy :: Int -> BufferAllocStrategy -- | An unsafe, but possibly more efficient buffer allocation strategy: -- reuse the buffer, if it is big enough for the next build step to -- execute. reuseBufferStrategy :: IO Buffer -> BufferAllocStrategy -- | Consume a source with a strict accumulator, in a way piecewise defined -- by a controlling stream. The latter will be evaluated until it -- terminates. -- --
--   >>> let f a s = liftM (:s) $ mapC (*a) =$ CL.take a
--   
--   >>> reverse $ runIdentity $ yieldMany [0..3] $$ mapAccumS f [] (yieldMany [1..])
--   [[],[1],[4,6],[12,15,18]] :: [[Int]]
--   
mapAccumS :: forall (m :: Type -> Type) a s b. Monad m => (a -> s -> ConduitT b Void m s) -> s -> ConduitT () b m () -> ConduitT a Void m s -- | Run a consuming conduit repeatedly, only stopping when there is no -- more data available from upstream. peekForever :: forall (m :: Type -> Type) i o. Monad m => ConduitT i o m () -> ConduitT i o m () -- | Run a consuming conduit repeatedly, only stopping when there is no -- more data available from upstream. -- -- In contrast to peekForever, this function will ignore empty -- chunks of data. So for example, if a stream of data contains an empty -- ByteString, it is still treated as empty, and the consuming -- function is not called. peekForeverE :: forall (m :: Type -> Type) i o. (Monad m, MonoFoldable i) => ConduitT i o m () -> ConduitT i o m () -- | Generate a producer from a seed value. unfoldC :: forall (m :: Type -> Type) b a i. Monad m => (b -> Maybe (a, b)) -> b -> ConduitT i a m () -- | Enumerate from a value to a final value, inclusive, via succ. -- -- This is generally more efficient than using Prelude's -- enumFromTo and combining with sourceList since this -- avoids any intermediate data structures. enumFromToC :: forall (m :: Type -> Type) a i. (Monad m, Enum a, Ord a) => a -> a -> ConduitT i a m () -- | Produces an infinite stream of repeated applications of f to x. iterateC :: forall (m :: Type -> Type) a i. Monad m => (a -> a) -> a -> ConduitT i a m () -- | Produce an infinite stream consisting entirely of the given value. repeatC :: forall (m :: Type -> Type) a i. Monad m => a -> ConduitT i a m () -- | Produce a finite stream consisting of n copies of the given value. replicateC :: forall (m :: Type -> Type) a i. Monad m => Int -> a -> ConduitT i a m () -- | Repeatedly run the given action and yield all values it produces. repeatMC :: Monad m => m a -> ConduitT i a m () -- | Repeatedly run the given action and yield all values it produces, -- until the provided predicate returns False. repeatWhileMC :: Monad m => m a -> (a -> Bool) -> ConduitT i a m () -- | Perform the given action n times, yielding each result. replicateMC :: Monad m => Int -> m a -> ConduitT i a m () -- | sourceHandle applied to stdin. stdinC :: forall (m :: Type -> Type) i. MonadIO m => ConduitT i ByteString m () -- | Ignore a certain number of values in the stream. -- -- Note: since this function doesn't produce anything, you probably want -- to use it with (>>) instead of directly plugging it into -- a pipeline: -- --
--   >>> runConduit $ yieldMany [1..5] .| dropC 2 .| sinkList
--   []
--   
--   >>> runConduit $ yieldMany [1..5] .| (dropC 2 >> sinkList)
--   [3,4,5]
--   
dropC :: forall (m :: Type -> Type) a o. Monad m => Int -> ConduitT a o m () -- | Drop a certain number of elements from a chunked stream. -- -- Note: you likely want to use it with monadic composition. See the docs -- for dropC. dropCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq) => Index seq -> ConduitT seq o m () -- | Drop all values which match the given predicate. -- -- Note: you likely want to use it with monadic composition. See the docs -- for dropC. dropWhileC :: forall (m :: Type -> Type) a o. Monad m => (a -> Bool) -> ConduitT a o m () -- | Drop all elements in the chunked stream which match the given -- predicate. -- -- Note: you likely want to use it with monadic composition. See the docs -- for dropC. dropWhileCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq) => (Element seq -> Bool) -> ConduitT seq o m () -- | Monoidally combine all values in the stream. foldC :: forall (m :: Type -> Type) a o. (Monad m, Monoid a) => ConduitT a o m a -- | Monoidally combine all elements in the chunked stream. foldCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono, Monoid (Element mono)) => ConduitT mono o m (Element mono) -- | A strict left fold. foldlC :: forall (m :: Type -> Type) a b o. Monad m => (a -> b -> a) -> a -> ConduitT b o m a -- | A strict left fold on a chunked stream. foldlCE :: forall (m :: Type -> Type) mono a o. (Monad m, MonoFoldable mono) => (a -> Element mono -> a) -> a -> ConduitT mono o m a -- | Apply the provided mapping function and monoidal combine all values. foldMapC :: forall (m :: Type -> Type) b a o. (Monad m, Monoid b) => (a -> b) -> ConduitT a o m b -- | Apply the provided mapping function and monoidal combine all elements -- of the chunked stream. foldMapCE :: forall (m :: Type -> Type) mono w o. (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono o m w -- | Check that all values in the stream return True. -- -- Subject to shortcut logic: at the first False, consumption of the -- stream will stop. allC :: forall (m :: Type -> Type) a o. Monad m => (a -> Bool) -> ConduitT a o m Bool -- | Check that all elements in the chunked stream return True. -- -- Subject to shortcut logic: at the first False, consumption of the -- stream will stop. allCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool -- | Check that at least one value in the stream returns True. -- -- Subject to shortcut logic: at the first True, consumption of the -- stream will stop. anyC :: forall (m :: Type -> Type) a o. Monad m => (a -> Bool) -> ConduitT a o m Bool -- | Check that at least one element in the chunked stream returns True. -- -- Subject to shortcut logic: at the first True, consumption of the -- stream will stop. anyCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool -- | Are all values in the stream True? -- -- Consumption stops once the first False is encountered. andC :: forall (m :: Type -> Type) o. Monad m => ConduitT Bool o m Bool -- | Are all elements in the chunked stream True? -- -- Consumption stops once the first False is encountered. andCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool -- | Are any values in the stream True? -- -- Consumption stops once the first True is encountered. orC :: forall (m :: Type -> Type) o. Monad m => ConduitT Bool o m Bool -- | Are any elements in the chunked stream True? -- -- Consumption stops once the first True is encountered. orCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool -- | Alternatively combine all values in the stream. asumC :: forall (m :: Type -> Type) f a o. (Monad m, Alternative f) => ConduitT (f a) o m (f a) -- | Are any values in the stream equal to the given value? -- -- Stops consuming as soon as a match is found. elemC :: forall (m :: Type -> Type) a o. (Monad m, Eq a) => a -> ConduitT a o m Bool -- | Are any elements in the chunked stream equal to the given element? -- -- Stops consuming as soon as a match is found. elemCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq, Eq (Element seq)) => Element seq -> ConduitT seq o m Bool -- | Are no values in the stream equal to the given value? -- -- Stops consuming as soon as a match is found. notElemC :: forall (m :: Type -> Type) a o. (Monad m, Eq a) => a -> ConduitT a o m Bool -- | Are no elements in the chunked stream equal to the given element? -- -- Stops consuming as soon as a match is found. notElemCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq, Eq (Element seq)) => Element seq -> ConduitT seq o m Bool -- | Take a single value from the stream, if available. headC :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m (Maybe a) -- | Same as headC, but returns a default value if none are -- available from the stream. headDefC :: forall (m :: Type -> Type) a o. Monad m => a -> ConduitT a o m a -- | Get the next element in the chunked stream. headCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) -- | View the next value in the stream without consuming it. peekC :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m (Maybe a) -- | View the next element in the chunked stream without consuming it. peekCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono) => ConduitT mono o m (Maybe (Element mono)) -- | Retrieve the last value in the stream, if present. lastC :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m (Maybe a) -- | Same as lastC, but returns a default value if none are -- available from the stream. lastDefC :: forall (m :: Type -> Type) a o. Monad m => a -> ConduitT a o m a -- | Retrieve the last element in the chunked stream, if present. lastCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) -- | Count how many values are in the stream. lengthC :: forall (m :: Type -> Type) len a o. (Monad m, Num len) => ConduitT a o m len -- | Count how many elements are in the chunked stream. lengthCE :: forall (m :: Type -> Type) len mono o. (Monad m, Num len, MonoFoldable mono) => ConduitT mono o m len -- | Count how many values in the stream pass the given predicate. lengthIfC :: forall (m :: Type -> Type) len a o. (Monad m, Num len) => (a -> Bool) -> ConduitT a o m len -- | Count how many elements in the chunked stream pass the given -- predicate. lengthIfCE :: forall (m :: Type -> Type) len mono o. (Monad m, Num len, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m len -- | Get the largest value in the stream, if present. maximumC :: forall (m :: Type -> Type) a o. (Monad m, Ord a) => ConduitT a o m (Maybe a) -- | Get the largest element in the chunked stream, if present. maximumCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) -- | Get the smallest value in the stream, if present. minimumC :: forall (m :: Type -> Type) a o. (Monad m, Ord a) => ConduitT a o m (Maybe a) -- | Get the smallest element in the chunked stream, if present. minimumCE :: forall (m :: Type -> Type) seq o. (Monad m, IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) -- | True if there are no values in the stream. -- -- This function does not modify the stream. nullC :: forall (m :: Type -> Type) a o. Monad m => ConduitT a o m Bool -- | True if there are no elements in the chunked stream. -- -- This function may remove empty leading chunks from the stream, but -- otherwise will not modify it. nullCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono) => ConduitT mono o m Bool -- | Get the sum of all values in the stream. sumC :: forall (m :: Type -> Type) a o. (Monad m, Num a) => ConduitT a o m a -- | Get the sum of all elements in the chunked stream. sumCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) -- | Get the product of all values in the stream. productC :: forall (m :: Type -> Type) a o. (Monad m, Num a) => ConduitT a o m a -- | Get the product of all elements in the chunked stream. productCE :: forall (m :: Type -> Type) mono o. (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) -- | Find the first matching value. findC :: forall (m :: Type -> Type) a o. Monad m => (a -> Bool) -> ConduitT a o m (Maybe a) -- | Apply the action to all values in the stream. -- -- Note: if you want to pass the values instead of -- consuming them, use iterM instead. mapM_C :: Monad m => (a -> m ()) -> ConduitT a o m () -- | Apply the action to all elements in the chunked stream. -- -- Note: the same caveat as with mapM_C applies. If you don't want -- to consume the values, you can use iterM: -- --
--   iterM (omapM_ f)
--   
mapM_CE :: (Monad m, MonoFoldable mono) => (Element mono -> m ()) -> ConduitT mono o m () -- | A monadic strict left fold. foldMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b o m a -- | A monadic strict left fold on a chunked stream. foldMCE :: (Monad m, MonoFoldable mono) => (a -> Element mono -> m a) -> a -> ConduitT mono o m a -- | Apply the provided monadic mapping function and monoidal combine all -- values. foldMapMC :: (Monad m, Monoid w) => (a -> m w) -> ConduitT a o m w -- | Apply the provided monadic mapping function and monoidal combine all -- elements in the chunked stream. foldMapMCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> m w) -> ConduitT mono o m w -- | Print all incoming values to stdout. printC :: forall a (m :: Type -> Type) o. (Show a, MonadIO m) => ConduitT a o m () -- | sinkHandle applied to stdout. stdoutC :: forall (m :: Type -> Type) o. MonadIO m => ConduitT ByteString o m () -- | sinkHandle applied to stderr. stderrC :: forall (m :: Type -> Type) o. MonadIO m => ConduitT ByteString o m () -- | Apply a transformation to all values in a stream. mapC :: forall (m :: Type -> Type) a b. Monad m => (a -> b) -> ConduitT a b m () -- | Apply a transformation to all elements in a chunked stream. mapCE :: forall (m :: Type -> Type) f a b. (Monad m, Functor f) => (a -> b) -> ConduitT (f a) (f b) m () -- | Apply a monomorphic transformation to all elements in a chunked -- stream. -- -- Unlike mapE, this will work on types like ByteString -- and Text which are MonoFunctor but not -- Functor. omapCE :: forall (m :: Type -> Type) mono. (Monad m, MonoFunctor mono) => (Element mono -> Element mono) -> ConduitT mono mono m () -- | Apply the function to each value in the stream, resulting in a -- foldable value (e.g., a list). Then yield each of the individual -- values in that foldable value separately. -- -- Generalizes concatMap, mapMaybe, and mapFoldable. concatMapC :: forall (m :: Type -> Type) mono a. (Monad m, MonoFoldable mono) => (a -> mono) -> ConduitT a (Element mono) m () -- | Apply the function to each element in the chunked stream, resulting in -- a foldable value (e.g., a list). Then yield each of the individual -- values in that foldable value separately. -- -- Generalizes concatMap, mapMaybe, and mapFoldable. concatMapCE :: forall (m :: Type -> Type) mono w. (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono w m () -- | Stream up to n number of values downstream. -- -- Note that, if downstream terminates early, not all values will be -- consumed. If you want to force exactly the given number of -- values to be consumed, see takeExactly. takeC :: forall (m :: Type -> Type) a. Monad m => Int -> ConduitT a a m () -- | Stream up to n number of elements downstream in a chunked stream. -- -- Note that, if downstream terminates early, not all values will be -- consumed. If you want to force exactly the given number of -- values to be consumed, see takeExactlyE. takeCE :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq) => Index seq -> ConduitT seq seq m () -- | Stream all values downstream that match the given predicate. -- -- Same caveats regarding downstream termination apply as with -- take. takeWhileC :: forall (m :: Type -> Type) a. Monad m => (a -> Bool) -> ConduitT a a m () -- | Stream all elements downstream that match the given predicate in a -- chunked stream. -- -- Same caveats regarding downstream termination apply as with -- takeE. takeWhileCE :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq) => (Element seq -> Bool) -> ConduitT seq seq m () -- | Consume precisely the given number of values and feed them downstream. -- -- This function is in contrast to take, which will only consume -- up to the given number of values, and will terminate early if -- downstream terminates early. This function will discard any additional -- values in the stream if they are unconsumed. -- -- Note that this function takes a downstream ConduitT as a -- parameter, as opposed to working with normal fusion. For more -- information, see -- http://www.yesodweb.com/blog/2013/10/core-flaw-pipes-conduit, -- the section titled "pipes and conduit: isolate". takeExactlyC :: forall (m :: Type -> Type) a b r. Monad m => Int -> ConduitT a b m r -> ConduitT a b m r -- | Same as takeExactly, but for chunked streams. takeExactlyCE :: forall (m :: Type -> Type) a b r. (Monad m, IsSequence a) => Index a -> ConduitT a b m r -> ConduitT a b m r -- | Flatten out a stream by yielding the values contained in an incoming -- MonoFoldable as individually yielded values. concatC :: forall (m :: Type -> Type) mono. (Monad m, MonoFoldable mono) => ConduitT mono (Element mono) m () -- | Keep only values in the stream passing a given predicate. filterC :: forall (m :: Type -> Type) a. Monad m => (a -> Bool) -> ConduitT a a m () -- | Keep only elements in the chunked stream passing a given predicate. filterCE :: forall seq (m :: Type -> Type). (IsSequence seq, Monad m) => (Element seq -> Bool) -> ConduitT seq seq m () -- | Map values as long as the result is Just. mapWhileC :: forall (m :: Type -> Type) a b. Monad m => (a -> Maybe b) -> ConduitT a b m () -- | Break up a stream of values into vectors of size n. The final vector -- may be smaller than n if the total number of values is not a strict -- multiple of n. No empty vectors will be yielded. conduitVector :: forall v a (m :: Type -> Type). (Vector v a, PrimMonad m) => Int -> ConduitT a (v a) m () -- | Analog of scanl for lists. scanlC :: forall (m :: Type -> Type) a b. Monad m => (a -> b -> a) -> a -> ConduitT b a m () -- | mapWhileC with a break condition dependent on a strict -- accumulator. Equivalently, mapAccum as long as the result is -- Right. Instead of producing a leftover, the breaking input -- determines the resulting accumulator via Left. mapAccumWhileC :: forall (m :: Type -> Type) a s b. Monad m => (a -> s -> Either s (s, b)) -> s -> ConduitT a b m s -- | concatMap with an accumulator. concatMapAccumC :: forall (m :: Type -> Type) a accum b. Monad m => (a -> accum -> (accum, [b])) -> accum -> ConduitT a b m () -- | Insert the given value between each two values in the stream. intersperseC :: forall (m :: Type -> Type) a. Monad m => a -> ConduitT a a m () -- | Sliding window of values 1,2,3,4,5 with window size 2 gives -- [1,2],[2,3],[3,4],[4,5] -- -- Best used with structures that support O(1) snoc. slidingWindowC :: forall (m :: Type -> Type) seq a. (Monad m, IsSequence seq, Element seq ~ a) => Int -> ConduitT a seq m () -- | Split input into chunk of size chunkSize -- -- The last element may be smaller than the chunkSize (see also -- chunksOfExactlyE which will not yield this last element) chunksOfCE :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq) => Index seq -> ConduitT seq seq m () -- | Split input into chunk of size chunkSize -- -- If the input does not split into chunks exactly, the remainder will be -- leftover (see also chunksOfE) chunksOfExactlyCE :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq) => Index seq -> ConduitT seq seq m () -- | Apply a monadic transformation to all values in a stream. -- -- If you do not need the transformed values, and instead just want the -- monadic side-effects of running the action, see mapM_. mapMC :: Monad m => (a -> m b) -> ConduitT a b m () -- | Apply a monadic transformation to all elements in a chunked stream. mapMCE :: (Monad m, Traversable f) => (a -> m b) -> ConduitT (f a) (f b) m () -- | Apply a monadic monomorphic transformation to all elements in a -- chunked stream. -- -- Unlike mapME, this will work on types like -- ByteString and Text which are MonoFunctor -- but not Functor. omapMCE :: (Monad m, MonoTraversable mono) => (Element mono -> m (Element mono)) -> ConduitT mono mono m () -- | Apply the monadic function to each value in the stream, resulting in a -- foldable value (e.g., a list). Then yield each of the individual -- values in that foldable value separately. -- -- Generalizes concatMapM, mapMaybeM, and mapFoldableM. concatMapMC :: (Monad m, MonoFoldable mono) => (a -> m mono) -> ConduitT a (Element mono) m () -- | Keep only values in the stream passing a given monadic predicate. filterMC :: Monad m => (a -> m Bool) -> ConduitT a a m () -- | Keep only elements in the chunked stream passing a given monadic -- predicate. filterMCE :: (Monad m, IsSequence seq) => (Element seq -> m Bool) -> ConduitT seq seq m () -- | Apply a monadic action on all values in a stream. -- -- This Conduit can be used to perform a monadic side-effect for -- every value, whilst passing the value through the Conduit -- as-is. -- --
--   iterM f = mapM (\a -> f a >>= \() -> return a)
--   
iterMC :: Monad m => (a -> m ()) -> ConduitT a a m () -- | Analog of scanl for lists, monadic. scanlMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b a m () -- | Monadic mapAccumWhileC. mapAccumWhileMC :: Monad m => (a -> s -> m (Either s (s, b))) -> s -> ConduitT a b m s -- | concatMapM with an accumulator. concatMapAccumMC :: Monad m => (a -> accum -> m (accum, [b])) -> accum -> ConduitT a b m () -- | Encode a stream of text as UTF8. encodeUtf8C :: forall (m :: Type -> Type) text binary. (Monad m, Utf8 text binary) => ConduitT text binary m () -- | Decode a stream of binary data as UTF8. decodeUtf8C :: forall (m :: Type -> Type). MonadThrow m => ConduitT ByteString Text m () -- | Decode a stream of binary data as UTF8, replacing any invalid bytes -- with the Unicode replacement character. decodeUtf8LenientC :: forall (m :: Type -> Type). Monad m => ConduitT ByteString Text m () -- | Stream in the entirety of a single line. -- -- Like takeExactly, this will consume the entirety of the line -- regardless of the behavior of the inner Conduit. lineC :: forall (m :: Type -> Type) seq o r. (Monad m, IsSequence seq, Element seq ~ Char) => ConduitT seq o m r -> ConduitT seq o m r -- | Same as line, but operates on ASCII/binary data. lineAsciiC :: forall (m :: Type -> Type) seq o r. (Monad m, IsSequence seq, Element seq ~ Word8) => ConduitT seq o m r -> ConduitT seq o m r -- | Insert a newline character after each incoming chunk of data. unlinesC :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () -- | Same as unlines, but operates on ASCII/binary data. unlinesAsciiC :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () -- | Convert a stream of arbitrarily-chunked textual data into a stream of -- data where each chunk represents a single line. Note that, if you have -- unknownuntrusted input, this function is unsafe/, since it -- would allow an attacker to form lines of massive length and exhaust -- memory. linesUnboundedC :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () -- | Same as linesUnbounded, but for ASCII/binary data. linesUnboundedAsciiC :: forall (m :: Type -> Type) seq. (Monad m, IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () -- | Generally speaking, yielding values from inside a Conduit requires -- some allocation for constructors. This can introduce an overhead, -- similar to the overhead needed to represent a list of values instead -- of a vector. This overhead is even more severe when talking about -- unboxed values. -- -- This combinator allows you to overcome this overhead, and efficiently -- fill up vectors. It takes two parameters. The first is the size of -- each mutable vector to be allocated. The second is a function. The -- function takes an argument which will yield the next value into a -- mutable vector. -- -- Under the surface, this function uses a number of tricks to get high -- performance. For more information on both usage and implementation, -- please see: -- https://www.fpcomplete.com/user/snoyberg/library-documentation/vectorbuilder vectorBuilderC :: forall (m :: Type -> Type) v e n i r. (PrimMonad m, Vector v e, PrimMonad n, PrimState m ~ PrimState n) => Int -> ((e -> n ()) -> ConduitT i Void m r) -> ConduitT i (v e) m r -- | Percent-encoding for URLs. -- -- Like urlEncode, but only makes the Builder. urlEncodeBuilder :: Bool -> ByteString -> Builder -- | Instead of (==). -- -- Since there was some confusion in the history of this library about -- how the Eq instance should work, it was removed for clarity, -- and replaced by equal and equiv. equal -- gives you equality of all fields of the Cookie record. equalCookie :: Cookie -> Cookie -> Bool -- | Equality of name, domain, path only. This corresponds to step 11 of -- the algorithm described in Section 5.3 "Storage Model". See also: -- equal. equivCookie :: Cookie -> Cookie -> Bool -- | Instead of instance Ord Cookie. See equalCookie, -- equivCookie. compareCookies :: Cookie -> Cookie -> Ordering -- | See equalCookie. equalCookieJar :: CookieJar -> CookieJar -> Bool -- | See equalCookieJar, equalCookie. equivCookieJar :: CookieJar -> CookieJar -> Bool -- | Create a new Connection from a read, write, and close function. makeConnection :: IO ByteString -> (ByteString -> IO ()) -> IO () -> IO Connection -- | Create a new Connection from a Socket. socketConnection :: Socket -> Int -> IO Connection -- | strippedHostName takes a URI host name, as extracted by -- regName, and strips square brackets around IPv6 addresses. -- -- The result is suitable for passing to services such as name resolution -- (getAddr). -- -- @since strippedHostName :: String -> String -- | Continuously call brRead, building up a lazy ByteString until a -- chunk is constructed that is at least as many bytes as requested. -- -- Since 0.4.20 brReadSome :: BodyReader -> Int -> IO ByteString -- | Deprecated synonym for parseUrlThrow. You probably want -- parseRequest or parseRequest_ instead. parseUrl :: MonadThrow m => String -> m Request -- | Same as parseRequest, except will throw an HttpException -- in the event of a non-2XX response. This uses -- throwErrorStatusCodes to implement checkResponse. parseUrlThrow :: MonadThrow m => String -> m Request -- | Throws a StatusCodeException wrapped in -- HttpExceptionRequest, if the response's status code indicates -- an error (if it isn't 2xx). This can be used to implement -- checkResponse. throwErrorStatusCodes :: MonadIO m => Request -> Response BodyReader -> m () -- | Convert a URL into a Request. -- -- This function defaults some of the values in Request, such as -- setting method to GET and requestHeaders -- to []. -- -- Since this function uses MonadThrow, the return monad can be -- anything that is an instance of MonadThrow, such as IO -- or Maybe. -- -- You can place the request method at the beginning of the URL separated -- by a space, e.g.: -- --
--   parseRequest "POST http://httpbin.org/post"
--   
-- -- Note that the request method must be provided as all capital letters. -- -- A Request created by this function won't cause exceptions on -- non-2XX response status codes. -- -- To create a request which throws on non-2XX status codes, see -- parseUrlThrow parseRequest :: MonadThrow m => String -> m Request -- | Same as parseRequest, but parse errors cause an impure -- exception. Mostly useful for static strings which are known to be -- correctly formatted. parseRequest_ :: String -> Request -- | Convert a URI into a Request. -- -- This can fail if the given URI is not absolute, or if the -- URI scheme is not "http" or "https". In these -- cases the function will throw an error via MonadThrow. -- -- This function defaults some of the values in Request, such as -- setting method to GET and requestHeaders -- to []. -- -- A Request created by this function won't cause exceptions on -- non-2XX response status codes. requestFromURI :: MonadThrow m => URI -> m Request -- | Same as requestFromURI, but if the conversion would fail, -- throws an impure exception. requestFromURI_ :: URI -> Request -- | Extract a URI from the request. -- -- Since 0.1.0 getUri :: Request -> URI -- | A default request value, a GET request of localhost/:80, with an empty -- request body. -- -- Note that the default checkResponse does nothing. defaultRequest :: Request -- | Add a Basic Auth header (with the specified user name and password) to -- the given Request. Ignore error handling: -- --
--   applyBasicAuth "user" "pass" $ parseRequest_ url
--   
-- -- NOTE: The function applyDigestAuth is provided by the -- http-client-tls package instead of this package due to extra -- dependencies. Please use that package if you need to use digest -- authentication. -- -- Since 0.1.0 applyBasicAuth :: ByteString -> ByteString -> Request -> Request -- | Add a Bearer Auth header to the given Request applyBearerAuth :: ByteString -> Request -> Request -- | Add a Proxy-Authorization header (with the specified username and -- password) to the given Request. Ignore error handling: -- --
--   applyBasicProxyAuth "user" "pass" <$> parseRequest "http://example.org"
--   
-- -- Since 0.3.4 applyBasicProxyAuth :: ByteString -> ByteString -> Request -> Request -- | Add url-encoded parameters to the Request. -- -- This sets a new requestBody, adds a content-type request header -- and changes the method to POST. -- -- Since 0.1.0 urlEncodedBody :: [(ByteString, ByteString)] -> Request -> Request -- | Modify the request so that non-2XX status codes do not generate a -- runtime StatusCodeException. setRequestIgnoreStatus :: Request -> Request -- | Modify the request so that non-2XX status codes generate a runtime -- StatusCodeException, by using throwErrorStatusCodes setRequestCheckStatus :: Request -> Request -- | Set the query string to the given key/value pairs. -- -- Since 0.3.6 setQueryString :: [(ByteString, Maybe ByteString)] -> Request -> Request -- | Set the query string to the given key/value pairs. setQueryStringPartialEscape :: [(ByteString, [EscapeItem])] -> Request -> Request -- | Send a file as the request body. -- -- It is expected that the file size does not change between calling -- streamFile and making any requests using this request body. -- -- Since 0.4.9 streamFile :: FilePath -> IO RequestBody -- | Send a file as the request body, while observing streaming progress -- via a PopObserver. Observations are made between reading and -- sending a chunk. -- -- It is expected that the file size does not change between calling -- observedStreamFile and making any requests using this request -- body. -- -- Since 0.4.9 observedStreamFile :: (StreamFileStatus -> IO ()) -> FilePath -> IO RequestBody -- | Retrieve the orignal Request from a Response -- -- Note that the requestBody is not available and always set to -- empty. getOriginalRequest :: Response a -> Request -- | A value for the managerRawConnection setting, but also allows -- you to modify the underlying Socket to set additional -- settings. For a motivating use case, see: -- https://github.com/snoyberg/http-client/issues/71. -- -- Since 0.3.8 rawConnectionModifySocket :: (Socket -> IO ()) -> IO (Maybe HostAddress -> String -> Int -> IO Connection) -- | Same as rawConnectionModifySocket, but also takes in a chunk -- size. rawConnectionModifySocketSize :: (Socket -> IO ()) -> IO (Int -> Maybe HostAddress -> String -> Int -> IO Connection) -- | Create, use and close a Manager. -- -- Since 0.2.1 withManager :: ManagerSettings -> (Manager -> IO a) -> IO a -- | Get the proxy settings from the Request itself. -- -- Since 0.4.7 proxyFromRequest :: ProxyOverride -- | Never connect using a proxy, regardless of the proxy value in the -- Request. -- -- Since 0.4.7 noProxy :: ProxyOverride -- | Use the given proxy settings, regardless of the proxy value in the -- Request. -- -- Since 0.4.7 useProxy :: Proxy -> ProxyOverride -- | Send secure requests to the proxy in plain text rather than using -- CONNECT, regardless of the value in the Request. useProxySecureWithoutConnect :: Proxy -> ProxyOverride -- | Get the proxy settings from the default environment variable -- (http_proxy for insecure, https_proxy for secure). -- If no variable is set, then fall back to the given value. -- Nothing is equivalent to noProxy, Just is -- equivalent to useProxy. -- -- Since 0.4.7 proxyEnvironment :: Maybe Proxy -> ProxyOverride -- | Same as proxyEnvironment, but instead of default environment -- variable names, allows you to set your own name. -- -- Since 0.4.7 proxyEnvironmentNamed :: Text -> Maybe Proxy -> ProxyOverride -- | The default proxy settings for a manager. In particular: if the -- http_proxy (or https_proxy) environment variable is -- set, use it. Otherwise, use the values in the Request. -- -- Since 0.4.7 defaultProxy :: ProxyOverride isIpAddress :: ByteString -> Bool -- | This corresponds to the subcomponent algorithm entitled "Domain -- Matching" detailed in section 5.1.3 domainMatches :: ByteString -> ByteString -> Bool -- | This corresponds to the subcomponent algorithm entitled "Paths" -- detailed in section 5.1.4 defaultPath :: Request -> ByteString -- | This corresponds to the subcomponent algorithm entitled "Path-Match" -- detailed in section 5.1.4 pathMatches :: ByteString -> ByteString -> Bool createCookieJar :: [Cookie] -> CookieJar destroyCookieJar :: CookieJar -> [Cookie] removeExistingCookieFromCookieJar :: Cookie -> CookieJar -> (Maybe Cookie, CookieJar) -- | Algorithm described in "Secure Contexts", Section 3.1, "Is origin -- potentially trustworthy?" -- -- Note per RFC6265 section 5.4 user agent is free to define the meaning -- of "secure" protocol. -- -- See: -- https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy isPotentiallyTrustworthyOrigin :: Bool -> ByteString -> Bool -- | This corresponds to the eviction algorithm described in Section 5.3 -- "Storage Model" evictExpiredCookies :: CookieJar -> UTCTime -> CookieJar -- | This applies the computeCookieString to a given Request insertCookiesIntoRequest :: Request -> CookieJar -> UTCTime -> (Request, CookieJar) -- | This corresponds to the algorithm described in Section 5.4 "The Cookie -- Header" computeCookieString :: Request -> CookieJar -> UTCTime -> Bool -> (ByteString, CookieJar) -- | This applies receiveSetCookie to a given Response updateCookieJar :: Response a -> Request -> UTCTime -> CookieJar -> (CookieJar, Response a) -- | This corresponds to the algorithm described in Section 5.3 "Storage -- Model" This function consists of calling generateCookie -- followed by insertCheckedCookie. Use this function if you plan -- to do both in a row. generateCookie and -- insertCheckedCookie are only provided for more fine-grained -- control. receiveSetCookie :: SetCookie -> Request -> UTCTime -> Bool -> CookieJar -> CookieJar -- | Insert a cookie created by generateCookie into the cookie jar (or not -- if it shouldn't be allowed in) insertCheckedCookie :: Cookie -> CookieJar -> Bool -> CookieJar -- | Turn a SetCookie into a Cookie, if it is valid generateCookie :: SetCookie -> Request -> UTCTime -> Bool -> Maybe Cookie -- | Perform an action using a Connection acquired from the given -- Manager. -- -- You should use this only when you have to read and write interactively -- through the connection (e.g. connection by the WebSocket protocol). withConnection :: Request -> Manager -> (Connection -> IO a) -> IO a -- | A variant of responseOpen which keeps a history of all -- redirects performed in the interim, together with the first 1024 bytes -- of their response bodies. -- -- Since 0.4.1 responseOpenHistory :: Request -> Manager -> IO (HistoriedResponse BodyReader) -- | A variant of withResponse which keeps a history of all -- redirects performed in the interim, together with the first 1024 bytes -- of their response bodies. -- -- Since 0.4.1 withResponseHistory :: Request -> Manager -> (HistoriedResponse BodyReader -> IO a) -> IO a -- | Set the proxy override value, only for HTTP (insecure) connections. -- -- Since 0.4.7 managerSetInsecureProxy :: ProxyOverride -> ManagerSettings -> ManagerSettings -- | Set the proxy override value, only for HTTPS (secure) connections. -- -- Since 0.4.7 managerSetSecureProxy :: ProxyOverride -> ManagerSettings -> ManagerSettings -- | Set the proxy override value, for both HTTP (insecure) and HTTPS -- (insecure) connections. -- -- Since 0.4.7 managerSetProxy :: ProxyOverride -> ManagerSettings -> ManagerSettings -- | Specify maximum time in microseconds the retrieval of response headers -- is allowed to take responseTimeoutMicro :: Int -> ResponseTimeout -- | Do not have a response timeout responseTimeoutNone :: ResponseTimeout -- | Use the default response timeout -- -- When used on a Request, means: use the manager's timeout value -- -- When used on a ManagerSettings, means: default to 30 seconds responseTimeoutDefault :: ResponseTimeout -- | Conduit powered version of withResponse. Differences are: -- -- -- -- Since 2.1.0 withResponse :: forall m (n :: Type -> Type) env i a. (MonadUnliftIO m, MonadIO n, MonadReader env m, HasHttpManager env) => Request -> (Response (ConduitM i ByteString n ()) -> m a) -> m a -- | An Acquire for getting a Response. -- -- Since 2.1.0 acquireResponse :: forall (n :: Type -> Type) env m i. (MonadIO n, MonadReader env m, HasHttpManager env) => Request -> m (Acquire (Response (ConduitM i ByteString n ()))) -- | TLS-powered manager settings. -- -- Since 2.1.0 defaultManagerSettings :: ManagerSettings -- | Get a new manager using defaultManagerSettings. -- -- Since 2.1.0 newManager :: MonadIO m => m Manager -- | Get a new manager using the given settings. -- -- Since 2.1.0 newManagerSettings :: MonadIO m => ManagerSettings -> m Manager -- | Conduit-powered version of responseOpen. -- -- See withResponse for the differences with responseOpen. -- -- Since 2.1.0 responseOpen :: forall m (n :: Type -> Type) env i. (MonadIO m, MonadIO n, MonadReader env m, HasHttpManager env) => Request -> m (Response (ConduitM i ByteString n ())) -- | Generalized version of responseClose. -- -- Since 2.1.0 responseClose :: MonadIO m => Response body -> m () bodyReaderSource :: forall (m :: Type -> Type) i. MonadIO m => BodyReader -> ConduitM i ByteString m () requestBodySource :: Int64 -> ConduitM () ByteString IO () -> RequestBody requestBodySourceChunked :: ConduitM () ByteString IO () -> RequestBody -- | Same as httpLbs, except it uses the Manager in the -- reader environment. -- -- Since 2.1.1 httpLbs :: (MonadIO m, HasHttpManager env, MonadReader env m) => Request -> m (Response ByteString) -- | Same as httpNoBody, except it uses the Manager in the -- reader environment. -- -- This can be more convenient that using withManager as it avoids -- the need to specify the base monad for the response body. -- -- Since 2.1.2 httpNoBody :: (MonadIO m, HasHttpManager env, MonadReader env m) => Request -> m (Response ()) -- | Same as httpSource, but uses Manager from Reader -- environment instead of the global one. -- -- Since 2.3.6 httpSource :: forall (m :: Type -> Type) (n :: Type -> Type) env r. (MonadResource m, MonadIO n, MonadReader env m, HasHttpManager env) => Request -> (Response (ConduitM () ByteString n ()) -> ConduitM () r m ()) -> ConduitM () r m () -- | Accept hAccept :: HeaderName -- | Accept-Language hAcceptLanguage :: HeaderName -- | Authorization hAuthorization :: HeaderName -- | Cache-Control hCacheControl :: HeaderName -- | Connection hConnection :: HeaderName -- | Content-Encoding hContentEncoding :: HeaderName -- | Content-Length hContentLength :: HeaderName -- | Content-MD5 -- -- This header has been obsoleted in RFC 9110. hContentMD5 :: HeaderName -- | Content-Type hContentType :: HeaderName -- | Date hDate :: HeaderName -- | If-Modified-Since hIfModifiedSince :: HeaderName -- | If-Range hIfRange :: HeaderName -- | Last-Modified hLastModified :: HeaderName -- | Location hLocation :: HeaderName -- | Range hRange :: HeaderName -- | Referer hReferer :: HeaderName -- | Server hServer :: HeaderName -- | User-Agent hUserAgent :: HeaderName -- | Cookie hCookie :: HeaderName -- | Turns a byte range into a byte string Builder. renderByteRangeBuilder :: ByteRange -> Builder -- | Renders a byte range into a ByteString. -- --
--   >>> renderByteRange (ByteRangeFrom 2048)
--   "2048-"
--   
renderByteRange :: ByteRange -> ByteString -- | Turns a list of byte ranges into a byte string Builder. renderByteRangesBuilder :: ByteRanges -> Builder -- | Renders a list of byte ranges into a ByteString. -- --
--   >>> renderByteRanges [ByteRangeFrom 2048, ByteRangeSuffix 20]
--   "bytes=2048-,-20"
--   
renderByteRanges :: ByteRanges -> ByteString -- | Parse the value of a Range header into a ByteRanges. -- --
--   >>> parseByteRanges "error"
--   Nothing
--   
--   >>> parseByteRanges "bytes=0-499"
--   Just [ByteRangeFromTo 0 499]
--   
--   >>> parseByteRanges "bytes=500-999"
--   Just [ByteRangeFromTo 500 999]
--   
--   >>> parseByteRanges "bytes=-500"
--   Just [ByteRangeSuffix 500]
--   
--   >>> parseByteRanges "bytes=9500-"
--   Just [ByteRangeFrom 9500]
--   
--   >>> parseByteRanges "bytes=0-0,-1"
--   Just [ByteRangeFromTo 0 0,ByteRangeSuffix 1]
--   
--   >>> parseByteRanges "bytes=500-600,601-999"
--   Just [ByteRangeFromTo 500 600,ByteRangeFromTo 601 999]
--   
--   >>> parseByteRanges "bytes=500-700,601-999"
--   Just [ByteRangeFromTo 500 700,ByteRangeFromTo 601 999]
--   
parseByteRanges :: ByteString -> Maybe ByteRanges -- | HTTP GET Method methodGet :: Method -- | HTTP POST Method methodPost :: Method -- | HTTP HEAD Method methodHead :: Method -- | HTTP PUT Method methodPut :: Method -- | HTTP DELETE Method methodDelete :: Method -- | HTTP TRACE Method methodTrace :: Method -- | HTTP CONNECT Method methodConnect :: Method -- | HTTP OPTIONS Method methodOptions :: Method -- | HTTP PATCH Method methodPatch :: Method -- | Convert a method ByteString to a StdMethod if -- possible. parseMethod :: Method -> Either ByteString StdMethod -- | Convert an algebraic method to a ByteString. -- --
--   renderMethod (parseMethod bs) == bs
--   
renderMethod :: Either ByteString StdMethod -> Method -- | Convert a StdMethod to a ByteString. renderStdMethod :: StdMethod -> Method -- | Create a Status from a status code and message. mkStatus :: Int -> ByteString -> Status -- | Continue 100 status100 :: Status -- | Continue 100 continue100 :: Status -- | Switching Protocols 101 status101 :: Status -- | Switching Protocols 101 switchingProtocols101 :: Status -- | OK 200 status200 :: Status -- | OK 200 ok200 :: Status -- | Created 201 status201 :: Status -- | Created 201 created201 :: Status -- | Accepted 202 status202 :: Status -- | Accepted 202 accepted202 :: Status -- | Non-Authoritative Information 203 status203 :: Status -- | Non-Authoritative Information 203 nonAuthoritative203 :: Status -- | No Content 204 status204 :: Status -- | No Content 204 noContent204 :: Status -- | Reset Content 205 status205 :: Status -- | Reset Content 205 resetContent205 :: Status -- | Partial Content 206 status206 :: Status -- | Partial Content 206 partialContent206 :: Status -- | Multiple Choices 300 status300 :: Status -- | Multiple Choices 300 multipleChoices300 :: Status -- | Moved Permanently 301 status301 :: Status -- | Moved Permanently 301 movedPermanently301 :: Status -- | Found 302 status302 :: Status -- | Found 302 found302 :: Status -- | See Other 303 status303 :: Status -- | See Other 303 seeOther303 :: Status -- | Not Modified 304 status304 :: Status -- | Not Modified 304 notModified304 :: Status -- | Use Proxy 305 status305 :: Status -- | Use Proxy 305 useProxy305 :: Status -- | Temporary Redirect 307 status307 :: Status -- | Temporary Redirect 307 temporaryRedirect307 :: Status -- | Permanent Redirect 308 status308 :: Status -- | Permanent Redirect 308 permanentRedirect308 :: Status -- | Bad Request 400 status400 :: Status -- | Bad Request 400 badRequest400 :: Status -- | Unauthorized 401 status401 :: Status -- | Unauthorized 401 unauthorized401 :: Status -- | Payment Required 402 status402 :: Status -- | Payment Required 402 paymentRequired402 :: Status -- | Forbidden 403 status403 :: Status -- | Forbidden 403 forbidden403 :: Status -- | Not Found 404 status404 :: Status -- | Not Found 404 notFound404 :: Status -- | Method Not Allowed 405 status405 :: Status -- | Method Not Allowed 405 methodNotAllowed405 :: Status -- | Not Acceptable 406 status406 :: Status -- | Not Acceptable 406 notAcceptable406 :: Status -- | Proxy Authentication Required 407 status407 :: Status -- | Proxy Authentication Required 407 proxyAuthenticationRequired407 :: Status -- | Request Timeout 408 status408 :: Status -- | Request Timeout 408 requestTimeout408 :: Status -- | Conflict 409 status409 :: Status -- | Conflict 409 conflict409 :: Status -- | Gone 410 status410 :: Status -- | Gone 410 gone410 :: Status -- | Length Required 411 status411 :: Status -- | Length Required 411 lengthRequired411 :: Status -- | Precondition Failed 412 status412 :: Status -- | Precondition Failed 412 preconditionFailed412 :: Status -- | Request Entity Too Large 413 status413 :: Status -- | Request Entity Too Large 413 requestEntityTooLarge413 :: Status -- | Request-URI Too Long 414 status414 :: Status -- | Request-URI Too Long 414 requestURITooLong414 :: Status -- | Unsupported Media Type 415 status415 :: Status -- | Unsupported Media Type 415 unsupportedMediaType415 :: Status -- | Requested Range Not Satisfiable 416 status416 :: Status -- | Requested Range Not Satisfiable 416 requestedRangeNotSatisfiable416 :: Status -- | Expectation Failed 417 status417 :: Status -- | Expectation Failed 417 expectationFailed417 :: Status -- | I'm a teapot 418 status418 :: Status -- | I'm a teapot 418 imATeapot418 :: Status -- | Unprocessable Entity 422 (RFC 4918) status422 :: Status -- | Unprocessable Entity 422 (RFC 4918) unprocessableEntity422 :: Status -- | Precondition Required 428 (RFC 6585) status428 :: Status -- | Precondition Required 428 (RFC 6585) preconditionRequired428 :: Status -- | Too Many Requests 429 (RFC 6585) status429 :: Status -- | Too Many Requests 429 (RFC 6585) tooManyRequests429 :: Status -- | Request Header Fields Too Large 431 (RFC 6585) status431 :: Status -- | Request Header Fields Too Large 431 (RFC 6585) requestHeaderFieldsTooLarge431 :: Status -- | Internal Server Error 500 status500 :: Status -- | Internal Server Error 500 internalServerError500 :: Status -- | Not Implemented 501 status501 :: Status -- | Not Implemented 501 notImplemented501 :: Status -- | Bad Gateway 502 status502 :: Status -- | Bad Gateway 502 badGateway502 :: Status -- | Service Unavailable 503 status503 :: Status -- | Service Unavailable 503 serviceUnavailable503 :: Status -- | Gateway Timeout 504 status504 :: Status -- | Gateway Timeout 504 gatewayTimeout504 :: Status -- | HTTP Version Not Supported 505 status505 :: Status -- | HTTP Version Not Supported 505 httpVersionNotSupported505 :: Status -- | Network Authentication Required 511 (RFC 6585) status511 :: Status -- | Network Authentication Required 511 (RFC 6585) networkAuthenticationRequired511 :: Status -- | Informational class -- -- Checks if the status is in the 1XX range. statusIsInformational :: Status -> Bool -- | Successful class -- -- Checks if the status is in the 2XX range. statusIsSuccessful :: Status -> Bool -- | Redirection class -- -- Checks if the status is in the 3XX range. statusIsRedirection :: Status -> Bool -- | Client Error class -- -- Checks if the status is in the 4XX range. statusIsClientError :: Status -> Bool -- | Server Error class -- -- Checks if the status is in the 5XX range. statusIsServerError :: Status -> Bool -- | Convert QueryText to Query. queryTextToQuery :: QueryText -> Query -- | Convert QueryText to a Builder. -- -- If you want a question mark (?) added to the front of the -- result, use True. renderQueryText :: Bool -> QueryText -> Builder -- | Convert Query to QueryText (leniently decoding the -- UTF-8). queryToQueryText :: Query -> QueryText -- | Parse a QueryText from a ByteString. See -- parseQuery for details. -- --
--   queryToQueryText . parseQuery
--   
parseQueryText :: ByteString -> QueryText -- | Convert SimpleQuery to Query. simpleQueryToQuery :: SimpleQuery -> Query -- | Renders the given Query into a Builder. -- -- If you want a question mark (?) added to the front of the -- result, use True. renderQueryBuilder :: Bool -> Query -> Builder -- | Renders the given Query into a ByteString. -- -- If you want a question mark (?) added to the front of the -- result, use True. renderQuery :: Bool -> Query -> ByteString -- | Render the given SimpleQuery into a ByteString. -- -- If you want a question mark (?) added to the front of the -- result, use True. renderSimpleQuery :: Bool -> SimpleQuery -> ByteString -- | Split out the query string into a list of keys and values. A few -- importants points: -- -- parseQuery :: ByteString -> Query -- | Same functionality as parseQuery, but with the option to decode -- '+' characters to ' ' or to preserve any -- '+' encountered. -- -- If you want to replace any '+' with a space, use True. parseQueryReplacePlus :: Bool -> ByteString -> Query -- | Parse SimpleQuery from a ByteString. -- -- This uses parseQuery under the hood, and will transform any -- Nothing values into an empty ByteString. parseSimpleQuery :: ByteString -> SimpleQuery -- | Percent-encoding for URLs. -- -- In short: -- -- -- --

In-depth explanation

-- -- This will substitute every byte with its percent-encoded equivalent -- unless: -- -- urlEncode :: Bool -> ByteString -> ByteString -- | Percent-decoding. -- -- If you want to replace any '+' with a space, use True. urlDecode :: Bool -> ByteString -> ByteString -- | Encodes a list of path segments into a valid URL fragment. -- -- This function takes the following three steps: -- -- -- -- For example: -- --
--   >>> encodePathSegments ["foo", "bar1", "~baz"]
--   "/foo/bar1/~baz"
--   
-- --
--   >>> encodePathSegments ["foo bar", "baz/bin"]
--   "/foo%20bar/baz%2Fbin"
--   
-- --
--   >>> encodePathSegments ["שלום"]
--   "/%D7%A9%D7%9C%D7%95%D7%9D"
--   
-- -- Huge thanks to Jeremy Shaw who created the original -- implementation of this function in web-routes and did such thorough -- research to determine all correct escaping procedures. encodePathSegments :: [Text] -> Builder -- | Like encodePathSegments, but without the initial slash. encodePathSegmentsRelative :: [Text] -> Builder -- | Parse a list of path segments from a valid URL fragment. -- -- Will also decode any percent-encoded characters. decodePathSegments :: ByteString -> [Text] -- | Extract whole path (path segments + query) from a RFC 2616 -- Request-URI. -- -- Though a more accurate description of this function's behaviour is -- that it removes the domain/origin if the string starts with an HTTP -- protocol. (i.e. http:// or https://) -- -- This function will not change anything when given any other -- ByteString. (except return a root path "/" if given an -- empty string) -- --
--   >>> extractPath "/path"
--   "/path"
--   
-- --
--   >>> extractPath "http://example.com:8080/path"
--   "/path"
--   
-- --
--   >>> extractPath "http://example.com"
--   "/"
--   
-- --
--   >>> extractPath ""
--   "/"
--   
-- --
--   >>> extractPath "www.google.com/some/path"
--   "www.google.com/some/path"
--   
extractPath :: ByteString -> ByteString -- | Encode a whole path (path segments + query). encodePath :: [Text] -> Query -> Builder -- | Decode a whole path (path segments + query). decodePath :: ByteString -> ([Text], Query) -- | Convert PartialEscapeQuery to ByteString. -- -- If you want a question mark (?) added to the front of the -- result, use True. -- --
--   >>> renderQueryPartialEscape True [("a", [QN "x:z + ", QE (encodeUtf8 "They said: \"שלום\"")])]
--   "?a=x:z + They%20said%3A%20%22%D7%A9%D7%9C%D7%95%D7%9D%22"
--   
renderQueryPartialEscape :: Bool -> PartialEscapeQuery -> ByteString -- | Convert a PartialEscapeQuery to a Builder. -- -- If you want a question mark (?) added to the front of the -- result, use True. renderQueryBuilderPartialEscape :: Bool -> PartialEscapeQuery -> Builder -- | HTTP 0.9 http09 :: HttpVersion -- | HTTP 1.0 http10 :: HttpVersion -- | HTTP 1.1 http11 :: HttpVersion -- | HTTP 2.0 http20 :: HttpVersion -- | Generates a function that takes a Text and logs a -- LevelDebug message. Usage: -- --
--   $(logDebug) "This is a debug log message"
--   
logDebug :: Q Exp -- | See logDebug logInfo :: Q Exp -- | See logDebug logWarn :: Q Exp -- | See logDebug logError :: Q Exp -- | Generates a function that takes a Text and logs a -- LevelOther message. Usage: -- --
--   $(logOther "My new level") "This is a log message"
--   
logOther :: Text -> Q Exp -- | Generates a function that takes a LogSource and Text and -- logs a LevelDebug message. Usage: -- --
--   $logDebugS "SomeSource" "This is a debug log message"
--   
logDebugS :: Q Exp -- | See logDebugS logInfoS :: Q Exp -- | See logDebugS logWarnS :: Q Exp -- | See logDebugS logErrorS :: Q Exp -- | Generates a function that takes a LogSource, a level name and a -- Text and logs a LevelOther message. Usage: -- --
--   $logOtherS "SomeSource" "My new level" "This is a log message"
--   
logOtherS :: Q Exp fromPersistValueText :: PersistValue -> Either Text Text fieldAttrsContainsNullable :: [FieldAttr] -> IsNullable -- | Return the [FieldDef] for the entity keys. entitiesPrimary :: EntityDef -> NonEmpty FieldDef entityPrimary :: EntityDef -> Maybe CompositeDef -- | Returns a NonEmpty list of FieldDef that correspond with -- the key columns for an EntityDef. keyAndEntityFields :: EntityDef -> NonEmpty FieldDef -- | Parse raw field attributes into structured form. Any unrecognized -- attributes will be preserved, identically as they are encountered, as -- FieldAttrOther values. parseFieldAttrs :: [Text] -> [FieldAttr] isFieldNotGenerated :: FieldDef -> Bool -- | Returns True if the FieldDef does not have a -- MigrationOnly or SafeToRemove flag from the -- QuasiQuoter. isHaskellField :: FieldDef -> Bool -- | A FieldCascade that does nothing. noCascade :: FieldCascade -- | Renders a FieldCascade value such that it can be used in SQL -- migrations. renderFieldCascade :: FieldCascade -> Text -- | Render a CascadeAction to Text such that it can be used -- in a SQL command. renderCascadeAction :: CascadeAction -> Text -- | Replace the FieldDef FieldAttr with the new list. setFieldAttrs :: [FieldAttr] -> FieldDef -> FieldDef -- | Modify the list of field attributes. overFieldAttrs :: ([FieldAttr] -> [FieldAttr]) -> FieldDef -> FieldDef -- | Add an attribute to the list of field attributes. addFieldAttr :: FieldAttr -> FieldDef -> FieldDef -- | Check if the field definition is nullable isFieldNullable :: FieldDef -> IsNullable -- | Check if the field is `Maybe a` isFieldMaybe :: FieldDef -> Bool -- | Retrieve the list of UniqueDef from an EntityDef. This -- does not include a Primary key, if one is defined. A future -- version of persistent will include a Primary key -- among the Unique constructors for the Entity. getEntityUniquesNoPrimaryKey :: EntityDef -> [UniqueDef] -- | Retrieve the list of UniqueDef from an EntityDef. As of -- version 2.14, this will also include the primary key on the entity, if -- one is defined. If you do not want the primary key, see -- getEntityUniquesNoPrimaryKey. getEntityUniques :: EntityDef -> [UniqueDef] -- | Retrieve the Haskell name of the given entity. getEntityHaskellName :: EntityDef -> EntityNameHS -- | Return the database name for the given entity. getEntityDBName :: EntityDef -> EntityNameDB getEntityExtra :: EntityDef -> Map Text [[Text]] setEntityDBName :: EntityNameDB -> EntityDef -> EntityDef getEntityComments :: EntityDef -> Maybe Text getEntityForeignDefs :: EntityDef -> [ForeignDef] -- | Retrieve the list of FieldDef that makes up the fields of the -- entity. -- -- This does not return the fields for an Id column or an -- implicit id. It will return the key columns if you used the -- Primary syntax for defining the primary key. -- -- This does not return fields that are marked SafeToRemove or -- MigrationOnly - so it only returns fields that are -- represented in the Haskell type. If you need those fields, use -- getEntityFieldsDatabase. getEntityFields :: EntityDef -> [FieldDef] -- | This returns all of the FieldDef defined for the -- EntityDef, including those fields that are marked as -- MigrationOnly (and therefore only present in the database) or -- SafeToRemove (and a migration will drop the column if it -- exists in the database). -- -- For all the fields that are present on the Haskell-type, see -- getEntityFields. getEntityFieldsDatabase :: EntityDef -> [FieldDef] isEntitySum :: EntityDef -> Bool getEntityId :: EntityDef -> EntityIdDef getEntityIdField :: EntityDef -> Maybe FieldDef -- | Set an entityId to be the given FieldDef. setEntityId :: FieldDef -> EntityDef -> EntityDef setEntityIdDef :: EntityIdDef -> EntityDef -> EntityDef getEntityKeyFields :: EntityDef -> NonEmpty FieldDef -- | Perform a mapping function over all of the entity fields, as -- determined by getEntityFieldsDatabase. overEntityFields :: ([FieldDef] -> [FieldDef]) -> EntityDef -> EntityDef -- | FIXME Add documentation to that. getPersistMap :: PersistValue -> Either Text [(Text, PersistValue)] -- | Construct an Entity record by providing a value for -- each of the record's fields. -- -- These constructions are equivalent: -- --
--   entityMattConstructor, entityMattTabulate :: Entity User
--   entityMattConstructor =
--       Entity
--           { entityKey = toSqlKey 123
--           , entityVal =
--               User
--                   { userName = Matt
--                   , userAge = 33
--                   }
--           }
--   
--   entityMattTabulate =
--       tabulateEntity $ \case
--           UserId ->
--               toSqlKey 123
--           UserName ->
--               Matt
--           UserAge ->
--               33
--   
-- -- This is a specialization of tabulateEntityA, which allows you -- to construct an Entity by providing an Applicative -- action for each field instead of a regular function. tabulateEntity :: PersistEntity record => (forall a. () => EntityField record a -> a) -> Entity record -- | Get list of values corresponding to given entity. entityValues :: PersistEntity record => Entity record -> [PersistValue] -- | Predefined toJSON. The resulting JSON looks like {"key": -- 1, "value": {"name": ...}}. -- -- The typical usage is: -- --
--   instance ToJSON (Entity User) where
--       toJSON = keyValueEntityToJSON
--   
keyValueEntityToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value -- | Predefined parseJSON. The input JSON looks like {"key": -- 1, "value": {"name": ...}}. -- -- The typical usage is: -- --
--   instance FromJSON (Entity User) where
--       parseJSON = keyValueEntityFromJSON
--   
keyValueEntityFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record) -- | Predefined toJSON. The resulting JSON looks like {"id": -- 1, "name": ...}. -- -- The typical usage is: -- --
--   instance ToJSON (Entity User) where
--       toJSON = entityIdToJSON
--   
entityIdToJSON :: (PersistEntity record, ToJSON record) => Entity record -> Value -- | Predefined parseJSON. The input JSON looks like {"id": 1, -- "name": ...}. -- -- The typical usage is: -- --
--   instance FromJSON (Entity User) where
--       parseJSON = entityIdFromJSON
--   
entityIdFromJSON :: (PersistEntity record, FromJSON record) => Value -> Parser (Entity record) -- | Convenience function for getting a free PersistField instance -- from a type with JSON instances. -- -- Example usage in combination with fromPersistValueJSON: -- --
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   
toPersistValueJSON :: ToJSON a => a -> PersistValue -- | Convenience function for getting a free PersistField instance -- from a type with JSON instances. The JSON parser used will accept JSON -- values other that object and arrays. So, if your instance serializes -- the data to a JSON string, this will still work. -- -- Example usage in combination with toPersistValueJSON: -- --
--   instance PersistField MyData where
--     fromPersistValue = fromPersistValueJSON
--     toPersistValue = toPersistValueJSON
--   
fromPersistValueJSON :: FromJSON a => PersistValue -> Either Text a -- | Run a query against a larger backend by plucking out BaseBackend -- backend -- -- This is a helper for reusing existing queries when expanding the -- backend type. withBaseBackend :: forall backend (m :: Type -> Type) a. HasPersistBackend backend => ReaderT (BaseBackend backend) m a -> ReaderT backend m a -- | Run a query against a compatible backend, by projecting the backend -- -- This is a helper for using queries which run against a specific -- backend type that your backend is compatible with. withCompatibleBackend :: forall sup sub (m :: Type -> Type) a. BackendCompatible sup sub => ReaderT sup m a -> ReaderT sub m a liftPersist :: (MonadIO m, MonadReader backend m) => ReaderT backend IO b -> m b -- | Same as get, but for a non-null (not Maybe) foreign key. Unsafe -- unless your database is enforcing that the foreign key is valid. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   getJustSpj :: MonadIO m => ReaderT SqlBackend m User
--   getJustSpj = getJust spjId
--   
-- --
--   spj <- getJust spjId
--   
-- -- The above query when applied on dataset-1, will get this -- record: -- --
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   
-- --
--   getJustUnknown :: MonadIO m => ReaderT SqlBackend m User
--   getJustUnknown = getJust unknownId
--   
-- -- mrx <- getJustUnknown -- -- This just throws an error. getJust :: forall record backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend record backend, MonadIO m) => Key record -> ReaderT backend m record -- | Same as getJust, but returns an Entity instead of just -- the record. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   getJustEntitySpj :: MonadIO m => ReaderT SqlBackend m (Entity User)
--   getJustEntitySpj = getJustEntity spjId
--   
-- --
--   spjEnt <- getJustEntitySpj
--   
-- -- The above query when applied on dataset-1, will get this -- entity: -- --
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   
getJustEntity :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, MonadIO m, PersistEntity record, PersistStoreRead backend) => Key record -> ReaderT backend m (Entity record) -- | Curry this to make a convenience function that loads an associated -- model. -- --
--   foreign = belongsTo foreignId
--   
belongsTo :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Maybe (Key ent2)) -> ent1 -> ReaderT backend m (Maybe ent2) -- | Same as belongsTo, but uses getJust and therefore is -- similarly unsafe. belongsToJust :: forall ent1 ent2 backend (m :: Type -> Type). (PersistStoreRead backend, PersistEntity ent1, PersistRecordBackend ent2 backend, MonadIO m) => (ent1 -> Key ent2) -> ent1 -> ReaderT backend m ent2 -- | Like insert, but returns the complete Entity. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   insertHaskellEntity :: MonadIO m => ReaderT SqlBackend m (Entity User)
--   insertHaskellEntity = insertEntity $ User "Haskell" 81
--   
-- --
--   haskellEnt <- insertHaskellEntity
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +----+---------+-----+
--   | id |  name   | age |
--   +----+---------+-----+
--   |  1 | SPJ     |  40 |
--   +----+---------+-----+
--   |  2 | Simon   |  41 |
--   +----+---------+-----+
--   |  3 | Haskell |  81 |
--   +----+---------+-----+
--   
insertEntity :: forall e backend (m :: Type -> Type). (PersistStoreWrite backend, PersistRecordBackend e backend, SafeToInsert e, MonadIO m, HasCallStack) => e -> ReaderT backend m (Entity e) -- | Like get, but returns the complete Entity. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   getSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
--   getSpjEntity = getEntity spjId
--   
-- --
--   mSpjEnt <- getSpjEntity
--   
-- -- The above query when applied on dataset-1, will get this -- entity: -- --
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   
getEntity :: forall e backend (m :: Type -> Type). (PersistStoreRead backend, PersistRecordBackend e backend, MonadIO m) => Key e -> ReaderT backend m (Maybe (Entity e)) -- | Like insertEntity but just returns the record instead of -- Entity. -- --

Example usage

-- -- With schema-1 and dataset-1, -- --
--   insertDaveRecord :: MonadIO m => ReaderT SqlBackend m User
--   insertDaveRecord = insertRecord $ User "Dave" 50
--   
-- --
--   dave <- insertDaveRecord
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+------+-----+
--   |id   |name  |age  |
--   +-----+------+-----+
--   |1    |SPJ   |40   |
--   +-----+------+-----+
--   |2    |Simon |41   |
--   +-----+------+-----+
--   |3    |Dave  |50   |
--   +-----+------+-----+
--   
insertRecord :: forall record backend (m :: Type -> Type). (PersistEntityBackend record ~ BaseBackend backend, PersistEntity record, MonadIO m, PersistStoreWrite backend, SafeToInsert record, HasCallStack) => record -> ReaderT backend m record -- | Given a proxy for a PersistEntity record, this returns the sole -- UniqueDef for that entity. onlyOneUniqueDef :: (OnlyOneUniqueKey record, Monad proxy) => proxy record -> UniqueDef -- | Like insertEntity, but returns Nothing when the record -- couldn't be inserted because of a uniqueness constraint. -- --

Example usage

-- -- We use schema-2 and dataset-1 here. -- --
--   insertUniqueSpjEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueSpjEntity = insertUniqueEntity $ User "SPJ" 50
--   
-- --
--   mSpjEnt <- insertUniqueSpjEntity
--   
-- -- The above query results Nothing as SPJ already exists. -- --
--   insertUniqueAlexaEntity :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity User))
--   insertUniqueAlexaEntity = insertUniqueEntity $ User "Alexa" 3
--   
-- --
--   mAlexaEnt <- insertUniqueSpjEntity
--   
-- -- Because there's no such unique keywords of the given record, the above -- query when applied on dataset-1, will produce this: -- --
--   +----+-------+-----+
--   | id | name  | age |
--   +----+-------+-----+
--   |  1 | SPJ   |  40 |
--   +----+-------+-----+
--   |  2 | Simon |  41 |
--   +----+-------+-----+
--   |  3 | Alexa |   3 |
--   +----+-------+-----+
--   
insertUniqueEntity :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueWrite backend, SafeToInsert record) => record -> ReaderT backend m (Maybe (Entity record)) -- | Return the single unique key for a record. -- --

Example usage

-- -- We use shcema-1 and dataset-1 here. -- --
--   onlySimonConst :: MonadIO m => ReaderT SqlBackend m (Unique User)
--   onlySimonConst = onlyUnique $ User "Simon" 999
--   
-- --
--   mSimonConst <- onlySimonConst
--   
-- -- mSimonConst would be Simon's uniqueness constraint. Note that -- onlyUnique doesn't work if there're more than two -- constraints. It will fail with a type error instead. onlyUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend record backend, OnlyOneUniqueKey record) => record -> ReaderT backend m (Unique record) -- | A modification of getBy, which takes the PersistEntity -- itself instead of a Unique record. Returns a record matching -- one of the unique keys. This function makes the most sense on -- entities with a single Unique constructor. -- --

Example usage

-- -- With schema-1 and dataset-1, -- -- getBySpjValue :: MonadIO m => ReaderT SqlBackend m (Maybe (Entity -- User)) getBySpjValue = getByValue $ User SPJ 999 -- --
--   mSpjEnt <- getBySpjValue
--   
-- -- The above query when applied on dataset-1, will get this -- record: -- --
--   +----+------+-----+
--   | id | name | age |
--   +----+------+-----+
--   |  1 | SPJ  |  40 |
--   +----+------+-----+
--   
getByValue :: forall record (m :: Type -> Type) backend. (MonadIO m, PersistUniqueRead backend, PersistRecordBackend record backend, AtLeastOneUniqueKey record) => record -> ReaderT backend m (Maybe (Entity record)) -- | Attempt to replace the record of the given key with the given new -- record. First query the unique fields to make sure the replacement -- maintains uniqueness constraints. -- -- Return Nothing if the replacement was made. If uniqueness is -- violated, return a Just with the Unique violation replaceUnique :: forall record backend (m :: Type -> Type). (MonadIO m, Eq (Unique record), PersistRecordBackend record backend, PersistUniqueWrite backend) => Key record -> record -> ReaderT backend m (Maybe (Unique record)) -- | Check whether there are any conflicts for unique keys with this entity -- and existing entities in the database. -- -- Returns Nothing if the entity would be unique, and could thus -- safely be inserted. on a conflict returns the conflicting key -- --

Example usage

-- -- We use schema-1 and dataset-1 here. -- -- This would be Nothing: -- --
--   mAlanConst <- checkUnique $ User "Alan" 70
--   
-- -- While this would be Just because SPJ already exists: -- --
--   mSpjConst <- checkUnique $ User "SPJ" 60
--   
checkUnique :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => record -> ReaderT backend m (Maybe (Unique record)) -- | Check whether there are any conflicts for unique keys with this entity -- and existing entities in the database. -- -- Returns Nothing if the entity would stay unique, and could thus -- safely be updated. on a conflict returns the conflicting key -- -- This is similar to checkUnique, except it's useful for updating -- - when the particular entity already exists, it would normally -- conflict with itself. This variant ignores those conflicts -- --

Example usage

-- -- We use schema-1 and dataset-1 here. -- -- This would be Nothing: -- --
--   mAlanConst <- checkUnique $ User "Alan" 70
--   
-- -- While this would be Just because SPJ already exists: -- --
--   mSpjConst <- checkUnique $ User "SPJ" 60
--   
checkUniqueUpdateable :: forall record backend (m :: Type -> Type). (MonadIO m, PersistRecordBackend record backend, PersistUniqueRead backend) => Entity record -> ReaderT backend m (Maybe (Unique record)) -- | Get all records matching the given criterion in the specified order. -- Returns also the identifiers. -- -- WARNING: This function returns a ConduitM, which suggests that -- it streams the results. It does not stream results on most backends. -- If you need streaming, see persistent-pagination for a means -- of chunking results based on indexed ranges. selectSource :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Entity record) m () -- | Get the Keys of all records matching the given criterion. -- -- For an example, see selectList. selectKeys :: forall record backend (m :: Type -> Type). (PersistQueryRead backend, MonadResource m, PersistRecordBackend record backend, MonadReader backend m) => [Filter record] -> [SelectOpt record] -> ConduitM () (Key record) m () -- | Returns a [Entity record] corresponding to the filters -- and options provided. -- -- Filters are constructed using the operators defined in -- Database.Persist (and re-exported from -- Database.Persist.Sql). Let's look at some examples: -- --
--   usersWithAgeOver40 :: SqlPersistT IO [Entity User]
--   usersWithAgeOver40 =
--       selectList [UserAge >=. 40] []
--   
-- -- If you provide multiple values in the list, the conditions are -- ANDed together. -- --
--   usersWithAgeBetween30And50 :: SqlPersistT IO [Entity User]
--   usersWithAgeBetween30And50 =
--        selectList
--            [ UserAge >=. 30
--            , UserAge <=. 50
--            ]
--            []
--   
-- -- The second list contains the SelectOpt for a record. We can -- select the first ten records with LimitTo -- --
--   firstTenUsers =
--       selectList [] [LimitTo 10]
--   
-- -- And we can select the second ten users with OffsetBy. -- --
--   secondTenUsers =
--       selectList [] [LimitTo 10, OffsetBy 10]
--   
-- -- Warning that LIMIT/OFFSET is bad for pagination! -- -- The type of record can usually be infered from the types of the -- provided filters and select options. In the previous two examples, -- though, you'll notice that the select options are polymorphic, -- applying to any record type. In order to help type inference in such -- situations, or simply as an enhancement to readability, you might find -- type application useful, illustrated below. -- --
--   {-# LANGUAGE TypeApplications #-}
--   ...
--   
--   firstTenUsers =
--       selectList User [] [LimitTo 10]
--   
--   secondTenUsers =
--       selectList User [] [LimitTo 10, OffsetBy 10]
--   
-- -- With Asc and Desc, we can provide the field we want to -- sort on. We can provide multiple sort orders - later ones are used to -- sort records that are equal on the first field. -- --
--   newestUsers =
--       selectList [] [Desc UserCreatedAt, LimitTo 10]
--   
--   oldestUsers =
--       selectList [] [Asc UserCreatedAt, LimitTo 10]
--   
selectList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Entity record] -- | Call selectKeys but return the result as a list. selectKeysList :: forall record backend (m :: Type -> Type). (MonadIO m, PersistQueryRead backend, PersistRecordBackend record backend) => [Filter record] -> [SelectOpt record] -> ReaderT backend m [Key record] -- | Assign a field a value. -- --

Examples

-- --
--   updateAge :: MonadIO m => ReaderT SqlBackend m ()
--   updateAge = updateWhere [UserName ==. "SPJ" ] [UserAge =. 45]
--   
-- -- Similar to updateWhere which is shown in the above example you -- can use other functions present in the module -- Database.Persist.Class. Note that the first parameter of -- updateWhere is [Filter val] and second parameter is -- [Update val]. By comparing this with the type of ==. and -- =., you can see that they match up in the above usage. -- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -> 45|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   
(=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Update v infixr 3 =. -- | Assign a field by addition (+=). -- --

Examples

-- --
--   addAge :: MonadIO m => ReaderT SqlBackend m ()
--   addAge = updateWhere [UserName ==. "SPJ" ] [UserAge +=. 1]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+---------+
--   |id   |name |age      |
--   +-----+-----+---------+
--   |1    |SPJ  |40 -> 41 |
--   +-----+-----+---------+
--   |2    |Simon|41       |
--   +-----+-----+---------+
--   
(+=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Update v infixr 3 +=. -- | Assign a field by subtraction (-=). -- --

Examples

-- --
--   subtractAge :: MonadIO m => ReaderT SqlBackend m ()
--   subtractAge = updateWhere [UserName ==. "SPJ" ] [UserAge -=. 1]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+---------+
--   |id   |name |age      |
--   +-----+-----+---------+
--   |1    |SPJ  |40 -> 39 |
--   +-----+-----+---------+
--   |2    |Simon|41       |
--   +-----+-----+---------+
--   
(-=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Update v infixr 3 -=. -- | Assign a field by multiplication (*=). -- --

Examples

-- --
--   multiplyAge :: MonadIO m => ReaderT SqlBackend m ()
--   multiplyAge = updateWhere [UserName ==. "SPJ" ] [UserAge *=. 2]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+--------+
--   |id   |name |age     |
--   +-----+-----+--------+
--   |1    |SPJ  |40 -> 80|
--   +-----+-----+--------+
--   |2    |Simon|41      |
--   +-----+-----+--------+
--   
(*=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Update v infixr 3 *=. -- | Assign a field by division (/=). -- --

Examples

-- --
--   divideAge :: MonadIO m => ReaderT SqlBackend m ()
--   divideAge = updateWhere [UserName ==. "SPJ" ] [UserAge /=. 2]
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+---------+
--   |id   |name |age      |
--   +-----+-----+---------+
--   |1    |SPJ  |40 -> 20 |
--   +-----+-----+---------+
--   |2    |Simon|41       |
--   +-----+-----+---------+
--   
(/=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Update v infixr 3 /=. -- | Check for equality. -- --

Examples

-- --
--   selectSPJ :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectSPJ = selectList [UserName ==. "SPJ" ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   
(==.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 ==. -- | Non-equality check. -- --

Examples

-- --
--   selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectSimon = selectList [UserName !=. "SPJ" ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   
(!=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 !=. -- | Less-than check. -- --

Examples

-- --
--   selectLessAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectLessAge = selectList [UserAge <. 41 ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   
(<.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 <. -- | Less-than or equal check. -- --

Examples

-- --
--   selectLessEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectLessEqualAge = selectList [UserAge <=. 40 ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   
(<=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 <=. -- | Greater-than check. -- --

Examples

-- --
--   selectGreaterAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectGreaterAge = selectList [UserAge >. 40 ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   
(>.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 >. -- | Greater-than or equal check. -- --

Examples

-- --
--   selectGreaterEqualAge :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectGreaterEqualAge = selectList [UserAge >=. 41 ] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   
(>=.) :: forall v typ. PersistField typ => EntityField v typ -> typ -> Filter v infix 4 >=. -- | Check if value is in given list. -- --

Examples

-- --
--   selectUsers :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectUsers = selectList [UserAge <-. [40, 41]] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   
-- --
--   selectSPJ :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectSPJ = selectList [UserAge <-. [40]] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |1    |SPJ  |40   |
--   +-----+-----+-----+
--   
(<-.) :: forall v typ. PersistField typ => EntityField v typ -> [typ] -> Filter v infix 4 <-. -- | Check if value is not in given list. -- --

Examples

-- --
--   selectSimon :: MonadIO m => ReaderT SqlBackend m [Entity User]
--   selectSimon = selectList [UserAge /<-. [40]] []
--   
-- -- The above query when applied on dataset-1, will produce this: -- --
--   +-----+-----+-----+
--   |id   |name |age  |
--   +-----+-----+-----+
--   |2    |Simon|41   |
--   +-----+-----+-----+
--   
(/<-.) :: forall v typ. PersistField typ => EntityField v typ -> [typ] -> Filter v infix 4 /<-. -- | The OR of two lists of filters. For example: -- --
--   selectList
--       ([ PersonAge >. 25
--        , PersonAge <. 30 ] ||.
--        [ PersonIncome >. 15000
--        , PersonIncome <. 25000 ])
--       []
--   
-- -- will filter records where a person's age is between 25 and 30 -- or a person's income is between (15000 and 25000). -- -- If you are looking for an (&&.) operator to do (A -- AND B AND (C OR D)) you can use the (++) operator -- instead as there is no (&&.). For example: -- --
--   selectList
--       ([ PersonAge >. 25
--        , PersonAge <. 30 ] ++
--       ([PersonCategory ==. 1] ||.
--        [PersonCategory ==. 5]))
--       []
--   
-- -- will filter records where a person's age is between 25 and 30 -- and (person's category is either 1 or 5). (||.) :: [Filter v] -> [Filter v] -> [Filter v] infixl 3 ||. -- | Convert list of PersistValues into textual representation of -- JSON object. This is a type-constrained synonym for toJsonText. listToJSON :: [PersistValue] -> Text -- | Convert map (list of tuples) into textual representation of JSON -- object. This is a type-constrained synonym for toJsonText. mapToJSON :: [(Text, PersistValue)] -> Text -- | A more general way to convert instances of ToJSON type class to -- strict text Text. toJsonText :: ToJSON j => j -> Text -- | FIXME What's this exactly? limitOffsetOrder :: PersistEntity val => [SelectOpt val] -> (Int, Int, [SelectOpt val]) -- | Runs a migration. If the migration fails to parse or if any of the -- migrations are unsafe, then this throws a -- PersistUnsafeMigrationException. runMigration :: forall (m :: Type -> Type). MonadIO m => Migration -> ReaderT SqlBackend m () -- | Converts a quasi-quoted syntax into a list of entity definitions, to -- be used as input to the template haskell generation code (mkPersist). persistWith :: PersistSettings -> QuasiQuoter -- | Apply persistWith to upperCaseSettings. persistUpperCase :: QuasiQuoter -- | Apply persistWith to lowerCaseSettings. persistLowerCase :: QuasiQuoter -- | Same as persistWith, but uses an external file instead of a -- quasiquotation. The recommended file extension is -- .persistentmodels. persistFileWith :: PersistSettings -> FilePath -> Q Exp -- | Same as persistFileWith, but uses several external files -- instead of one. Splitting your Persistent definitions into multiple -- modules can potentially dramatically speed up compile times. -- -- The recommended file extension is .persistentmodels. -- --

Examples

-- -- Split your Persistent definitions into multiple files -- (models1, models2), then create a new module for -- each new file and run mkPersist there: -- --
--   -- Model1.hs
--   share
--       [mkPersist sqlSettings]
--       $(persistFileWith lowerCaseSettings "models1")
--   
-- --
--   -- Model2.hs
--   share
--       [mkPersist sqlSettings]
--       $(persistFileWith lowerCaseSettings "models2")
--   
-- -- Use persistManyFileWith to create your migrations: -- --
--   -- Migrate.hs
--   mkMigrate "migrateAll"
--       $(persistManyFileWith lowerCaseSettings ["models1.persistentmodels","models2.persistentmodels"])
--   
-- -- Tip: To get the same import behavior as if you were declaring all your -- models in one file, import your new files as Name into -- another file, then export module Name. -- -- This approach may be used in the future to reduce memory usage during -- compilation, but so far we've only seen mild reductions. -- -- See persistent#778 and persistent#791 for more details. persistManyFileWith :: PersistSettings -> [FilePath] -> Q Exp -- | Takes a list of (potentially) independently defined entities and -- properly links all foreign keys to reference the right -- EntityDef, tying the knot between entities. -- -- Allows users to define entities indepedently or in separate modules -- and then fix the cross-references between them at runtime to create a -- Migration. embedEntityDefs :: [EntityDef] -> [UnboundEntityDef] -> [UnboundEntityDef] -- | Calls parse to Quasi.parse individual entities in isolation -- afterwards, sets references to other entities -- -- In 2.13.0.0, this was changed to splice in -- [UnboundEntityDef] instead of -- [EntityDef]. parseReferences :: PersistSettings -> Text -> Q Exp -- | Create data types and appropriate PersistEntity instances for -- the given UnboundEntityDefs. -- -- This function should be used if you are only defining a single block -- of Persistent models for the entire application. If you intend on -- defining multiple blocks in different fiels, see mkPersistWith -- which allows you to provide existing entity definitions so foreign key -- references work. -- -- Example: -- --
--   mkPersist sqlSettings [persistLowerCase|
--        User
--            name    Text
--            age     Int
--   
--        Dog
--            name    Text
--            owner   UserId
--   
--   |]
--   
-- -- Example from a file: -- --
--   mkPersist sqlSettings $(persistFileWith lowerCaseSettings "models.persistentmodels")
--   
-- -- For full information on the QuasiQuoter syntax, see -- Database.Persist.Quasi documentation. mkPersist :: MkPersistSettings -> [UnboundEntityDef] -> Q [Dec] -- | Like mkPersist, but allows you to provide a -- [EntityDef] representing the predefined entities. This -- function will include those EntityDef when looking for foreign -- key references. -- -- You should use this if you intend on defining Persistent models in -- multiple files. -- -- Suppose we define a table Foo which has no dependencies. -- --
--   module DB.Foo where
--   
--       mkPersistWith sqlSettings [] [persistLowerCase|
--           Foo
--              name    Text
--          |]
--   
-- -- Then, we define a table Bar which depends on Foo: -- --
--   module DB.Bar where
--   
--       import DB.Foo
--   
--       mkPersistWith sqlSettings [entityDef (Proxy :: Proxy Foo)] [persistLowerCase|
--           Bar
--               fooId  FooId
--        |]
--   
-- -- Writing out the list of EntityDef can be annoying. The -- $(discoverEntities) shortcut will work to reduce this -- boilerplate. -- --
--   module DB.Quux where
--   
--       import DB.Foo
--       import DB.Bar
--   
--       mkPersistWith sqlSettings $(discoverEntities) [persistLowerCase|
--           Quux
--               name     Text
--               fooId    FooId
--               barId    BarId
--        |]
--   
mkPersistWith :: MkPersistSettings -> [EntityDef] -> [UnboundEntityDef] -> Q [Dec] -- | Set the ImplicitIdDef in the given MkPersistSettings. -- The default value is autoIncrementingInteger. setImplicitIdDef :: ImplicitIdDef -> MkPersistSettings -> MkPersistSettings -- | Create an MkPersistSettings with default values. mkPersistSettings :: Type -> MkPersistSettings -- | Use the SqlPersist backend. sqlSettings :: MkPersistSettings lensPTH :: (s -> a) -> (s -> b -> t) -> Lens s t a b -- | Returns True if the key definition has less than 2 fields. pkNewtype :: MkPersistSettings -> UnboundEntityDef -> Bool -- | Render an error message based on the tableName and -- fieldName with the provided message. fieldError :: Text -> Text -> Text -> Text -- | Produce code similar to the following: -- --
--   instance PersistEntity e => PersistField e where
--      toPersistValue = entityToPersistValueHelper
--      fromPersistValue = entityFromPersistValueHelper ["col1", "col2"]
--      sqlType _ = SqlString
--   
persistFieldFromEntity :: MkPersistSettings -> UnboundEntityDef -> Q [Dec] -- | Apply the given list of functions to the same EntityDefs. -- -- This function is useful for cases such as: -- --
--   share [mkEntityDefList "myDefs", mkPersist sqlSettings] [persistLowerCase|
--       -- ...
--   |]
--   
-- -- If you only have a single function, though, you don't need this. The -- following is redundant: -- --
--   share [mkPersist sqlSettings] [persistLowerCase|
--        -- ...
--   |]
--   
-- -- Most functions require a full [EntityDef], which can -- be provided using $(discoverEntities) for all entites -- in scope, or defining mkEntityDefList to define a list of -- entities from the given block. share :: [[a] -> Q [Dec]] -> [a] -> Q [Dec] -- | Creates a declaration for the [EntityDef] from the -- persistent schema. This is necessary because the Persistent -- QuasiQuoter is unable to know the correct type of ID fields, and -- assumes that they are all Int64. -- -- Provide this in the list you give to share, much like -- mkMigrate. -- --
--   share [mkMigrate "migrateAll", mkEntityDefList "entityDefs"] [...]
--   
mkEntityDefList :: String -> [UnboundEntityDef] -> Q [Dec] -- | Automatically creates a valid PersistField instance for any -- datatype that has valid Show and Read instances. Can be -- very convenient for Enum types. derivePersistField :: String -> Q [Dec] -- | Automatically creates a valid PersistField instance for any -- datatype that has valid ToJSON and FromJSON instances. -- For a datatype T it generates instances similar to these: -- --
--   instance PersistField T where
--       toPersistValue = PersistByteString . L.toStrict . encode
--       fromPersistValue = (left T.pack) . eitherDecodeStrict' <=< fromPersistValue
--   instance PersistFieldSql T where
--       sqlType _ = SqlString
--   
derivePersistFieldJSON :: String -> Q [Dec] -- | The basic function for migrating models, no Template Haskell required. -- -- It's probably best to use this in concert with mkEntityDefList, -- and then call migrateModels with the result from that function. -- --
--   share [mkPersist sqlSettings, mkEntityDefList "entities"] [persistLowerCase| ... |]
--   
--   migrateAll = migrateModels entities
--   
-- -- The function mkMigrate currently implements exactly this -- behavior now. If you're splitting up the entity definitions into -- separate files, then it is better to use the entity definition list -- and the concatenate all the models together into a big list to call -- with migrateModels. -- --
--   module Foo where
--   
--       share [mkPersist s, mkEntityDefList "fooModels"] ...
--   
--   
--   module Bar where
--   
--       share [mkPersist s, mkEntityDefList "barModels"] ...
--   
--   module Migration where
--   
--       import Foo
--       import Bar
--   
--       migrateAll = migrateModels (fooModels <> barModels)
--   
migrateModels :: [EntityDef] -> Migration -- | Creates a single function to perform all migrations for the entities -- defined here. One thing to be aware of is dependencies: if you have -- entities with foreign references, make sure to place those definitions -- after the entities they reference. -- -- In persistent-2.13.0.0, this was changed to *ignore* the -- input entity def list, and instead defer to mkEntityDefList to -- get the correct entities. This avoids problems where the QuasiQuoter -- is unable to know what the right reference types are. This sets -- mkPersist to be the "single source of truth" for entity -- definitions. mkMigrate :: String -> [UnboundEntityDef] -> Q [Dec] -- | Splice in a list of all EntityDef in scope. This is useful when -- running mkPersist to ensure that all entity definitions are -- available for setting foreign keys, and for performing migrations with -- all entities available. -- -- mkPersist has the type MkPersistSettings -> [EntityDef] -- -> DecsQ. So, to account for entities defined elsewhere, -- you'll mappend $(discoverEntities). -- -- For example, -- --
--   share
--     [ mkPersistWith sqlSettings $(discoverEntities)
--     ]
--     [persistLowerCase| ... |]
--   
-- -- Likewise, to run migrations with all entity instances in scope, you'd -- write: -- --
--   migrateAll = migrateModels $(discoverEntities)
--   
-- -- Note that there is some odd behavior with Template Haskell and -- splicing groups. If you call discoverEntities in the same -- module that defines PersistEntity instances, you need to ensure -- they are in different top-level binding groups. You can write -- $(pure []) at the top level to do this. -- --
--   -- Foo and Bar both export an instance of PersistEntity
--   import Foo
--   import Bar
--   
--   -- Since Foo and Bar are both imported, discoverEntities can find them here.
--   mkPersistWith sqlSettings $(discoverEntities) [persistLowerCase|
--     User
--       name Text
--       age  Int
--     |]
--   
--   -- onlyFooBar is defined in the same 'top level group' as the above generated
--   -- instance for User, so it isn't present in this list.
--   onlyFooBar :: [EntityDef]
--   onlyFooBar = $(discoverEntities)
--   
--   -- We can manually create a new binding group with this, which splices an
--   -- empty list of declarations in.
--   $(pure [])
--   
--   -- fooBarUser is able to see the User instance.
--   fooBarUser :: [EntityDef]
--   fooBarUser = $(discoverEntities)
--   
discoverEntities :: Q Exp -- | render with route interpolation. If using this module standalone, -- apart from type-safe routes, a dummy renderer can be used: -- --
--   renderJavascriptUrl (\_ _ -> undefined) javascriptUrl
--   
-- -- When using Yesod, a renderer is generated for you, which can be -- accessed within the GHandler monad: getUrlRenderParams. renderJavascriptUrl :: (url -> [(Text, Text)] -> Text) -> JavascriptUrl url -> Text julius :: QuasiQuoter renderCssUrl :: (url -> [(Text, Text)] -> Text) -> CssUrl url -> Text -- |
--   >>> renderCss ([lucius|foo{bar:baz}|] undefined)
--   "foo{bar:baz}"
--   
lucius :: QuasiQuoter -- | "Simple Hamlet" quasi-quoter. May only be used to generate -- expressions. -- -- Generated expressions have type Html. -- --
--   >>> putStrLn (renderHtml [shamlet|<div>Hello, world!|])
--   <div>Hello, world!</div>
--   
shamlet :: QuasiQuoter -- | Hamlet quasi-quoter. May only be used to generate expressions. -- -- Generated expression have type HtmlUrl url, for some -- url. -- --
--   data MyRoute = Home
--   
--   render :: Render MyRoute
--   render Home _ = "/home"
--   
--   >>> putStrLn (renderHtml ([hamlet|<a href=@{Home}>Home|] render))
--   <a href="/home">Home</a>
--   
hamlet :: QuasiQuoter -- | Like hamlet, but produces XHTML. xhamlet :: QuasiQuoter cassius :: QuasiQuoter -- | generate translations from translation files -- -- This function will: -- --
    --
  1. look in the supplied subdirectory for files ending in -- .msg
  2. --
  3. generate a type based on the constructors found
  4. --
  5. create a RenderMessage instance
  6. --
mkMessage :: String -> FilePath -> Lang -> Q [Dec] -- | create RenderMessage instance for an existing data-type mkMessageFor :: String -> String -> FilePath -> Lang -> Q [Dec] -- | create an additional set of translations for a type created by -- mkMessage mkMessageVariant :: String -> String -> FilePath -> Lang -> Q [Dec] -- | The URL rendering function with query-string parameters. getUrlRenderParams :: MonadHandler m => m (Route (HandlerSite m) -> [(Text, Text)] -> Text) -- | Guess the approot based on request headers. For more information, see -- Network.Wai.Middleware.Approot -- -- In the case of headers being unavailable, it falls back to -- ApprootRelative -- -- Since 1.4.16 guessApproot :: Approot site -- | Deprecated synonym for addHeader. setHeader :: MonadHandler m => Text -> Text -> m () -- | Bypass remaining handler code and output the given file. -- -- For some backends, this is more efficient than reading in the file to -- memory, since they can optimize file sending via a system call to -- sendfile. sendFile :: MonadHandler m => ContentType -> FilePath -> m a -- | Bypass remaining handler code and output the given content with a 200 -- status code. sendResponse :: (MonadHandler m, ToTypedContent c) => c -> m a -- | Format a UTCTime in W3 format. formatW3 :: UTCTime -> Text -- | Format as per RFC 1123. formatRFC1123 :: UTCTime -> Text -- | Format as per RFC 822. formatRFC822 :: UTCTime -> Text clientSessionDateCacher :: NominalDiffTime -> IO (IO ClientSessionDateCache, IO ()) -- | Zero-length enumerator. emptyContent :: Content repJson :: ToContent a => a -> RepJson repPlain :: ToContent a => a -> RepPlain repXml :: ToContent a => a -> RepXml typeHtml :: ContentType typePlain :: ContentType typeJson :: ContentType typeXml :: ContentType typeAtom :: ContentType typeRss :: ContentType typeJpeg :: ContentType typePng :: ContentType typeGif :: ContentType typeSvg :: ContentType typeJavascript :: ContentType typeCss :: ContentType typeFlv :: ContentType typeOgv :: ContentType typeOctet :: ContentType -- | Removes "extra" information at the end of a content type string. In -- particular, removes everything after the semicolon, if present. -- -- For example, "text/html; charset=utf-8" is commonly used to specify -- the character encoding for HTML data. This function would return -- "text/html". simpleContentType :: ContentType -> ContentType -- | Give just the media types as a pair. -- -- For example, "text/html; charset=utf-8" returns ("text", "html") contentTypeTypes :: ContentType -> (ByteString, ByteString) getRequest :: MonadHandler m => m YesodRequest runRequestBody :: MonadHandler m => m RequestBodyContents -- | Get the master site application argument. getYesod :: MonadHandler m => m (HandlerSite m) -- | Get a specific component of the master site application argument. -- Analogous to the gets function for operating on -- StateT. getsYesod :: MonadHandler m => (HandlerSite m -> a) -> m a -- | Get the URL rendering function. getUrlRender :: MonadHandler m => m (Route (HandlerSite m) -> Text) -- | Get all the post parameters passed to the handler. To also get the -- submitted files (if any), you have to use runRequestBody -- instead of this function. getPostParams :: MonadHandler m => m [(Text, Text)] -- | Get the route requested by the user. If this is a 404 response- where -- the user requested an invalid route- this function will return -- Nothing. getCurrentRoute :: MonadHandler m => m (Maybe (Route (HandlerSite m))) -- | Returns a function that runs HandlerFor actions inside -- IO. -- -- Sometimes you want to run an inner HandlerFor action outside -- the control flow of an HTTP request (on the outer HandlerFor -- action). For example, you may want to spawn a new thread: -- --
--   getFooR :: Handler RepHtml
--   getFooR = do
--     runInnerHandler <- handlerToIO
--     liftIO $ forkIO $ runInnerHandler $ do
--       Code here runs inside HandlerFor but on a new thread.
--       This is the inner HandlerFor.
--       ...
--     Code here runs inside the request's control flow.
--     This is the outer HandlerFor.
--     ...
--   
-- -- Another use case for this function is creating a stream of server-sent -- events using HandlerFor actions (see -- yesod-eventsource). -- -- Most of the environment from the outer HandlerFor is preserved -- on the inner HandlerFor, however: -- -- -- -- Changes to the response made inside the inner HandlerFor are -- ignored (e.g., session variables, cookies, response headers). This -- allows the inner HandlerFor to outlive the outer -- HandlerFor (e.g., on the forkIO example above, a -- response may be sent to the client without killing the new thread). handlerToIO :: MonadIO m => HandlerFor site (HandlerFor site a -> m a) -- | forkIO for a Handler (run an action in the background) -- -- Uses handlerToIO, liftResourceT, and resourceForkIO for -- correctness and efficiency forkHandler :: (SomeException -> HandlerFor site ()) -> HandlerFor site () -> HandlerFor site () -- | Redirect to the given route. HTTP status code 303 for HTTP 1.1 clients -- and 302 for HTTP 1.0 This is the appropriate choice for a -- get-following-post technique, which should be the usual use case. -- -- If you want direct control of the final status code, or need a -- different status code, please use redirectWith. redirect :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m a -- | Redirect to the given URL with the specified status code. redirectWith :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => Status -> url -> m a -- | Sets the ultimate destination variable to the given route. -- -- An ultimate destination is stored in the user session and can be -- loaded later by redirectUltDest. setUltDest :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m () -- | Same as setUltDest, but uses the current page. -- -- If this is a 404 handler, there is no current page, and then this call -- does nothing. setUltDestCurrent :: MonadHandler m => m () -- | Sets the ultimate destination to the referer request header, if -- present. -- -- This function will not overwrite an existing ultdest. setUltDestReferer :: MonadHandler m => m () -- | Redirect to the ultimate destination in the user's session. Clear the -- value from the session. -- -- The ultimate destination is set with setUltDest. -- -- This function uses redirect, and thus will perform a temporary -- redirect to a GET request. redirectUltDest :: (RedirectUrl (HandlerSite m) url, MonadHandler m) => url -> m a -- | Remove a previously set ultimate destination. See setUltDest. clearUltDest :: MonadHandler m => m () -- | Adds a status and message in the user's session. -- -- See getMessages. addMessage :: MonadHandler m => Text -> Html -> m () -- | Adds a message in the user's session but uses RenderMessage to allow -- for i18n -- -- See getMessages. addMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => Text -> msg -> m () -- | Gets all messages in the user's session, and then clears the variable. -- -- See addMessage. getMessages :: MonadHandler m => m [(Text, Html)] -- | Calls addMessage with an empty status setMessage :: MonadHandler m => Html -> m () -- | Calls addMessageI with an empty status setMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => msg -> m () -- | Gets just the last message in the user's session, discards the rest -- and the status getMessage :: MonadHandler m => m (Maybe Html) -- | Same as sendFile, but only sends part of a file. sendFilePart :: MonadHandler m => ContentType -> FilePath -> Integer -> Integer -> m a -- | Bypass remaining handler code and output the given content with the -- given status code. sendResponseStatus :: (MonadHandler m, ToTypedContent c) => Status -> c -> m a -- | Bypass remaining handler code and output the given JSON with the given -- status code. sendStatusJSON :: (MonadHandler m, ToJSON c) => Status -> c -> m a -- | Send a 201 Created response with the given route as the -- Location response header. sendResponseCreated :: MonadHandler m => Route (HandlerSite m) -> m a -- | Bypass remaining handler code and output no content with a 204 status -- code. sendResponseNoContent :: MonadHandler m => m a -- | Send a Response. Please note: this function is rarely -- necessary, and will disregard any changes to response headers -- and session that you have already specified. This function -- short-circuits. It should be considered only for very specific needs. -- If you are not sure if you need it, you don't. sendWaiResponse :: MonadHandler m => Response -> m b -- | Switch over to handling the current request with a WAI -- Application. sendWaiApplication :: MonadHandler m => Application -> m b -- | Send a raw response without conduit. This is used for cases such as -- WebSockets. Requires WAI 3.0 or later, and a web server which supports -- raw responses (e.g., Warp). sendRawResponseNoConduit :: (MonadHandler m, MonadUnliftIO m) => (IO ByteString -> (ByteString -> IO ()) -> m ()) -> m a -- | Send a raw response. This is used for cases such as WebSockets. -- Requires WAI 2.1 or later, and a web server which supports raw -- responses (e.g., Warp). sendRawResponse :: (MonadHandler m, MonadUnliftIO m) => (ConduitT () ByteString IO () -> ConduitT ByteString Void IO () -> m ()) -> m a -- | Send a 304 not modified response immediately. This is a -- short-circuiting action. notModified :: MonadHandler m => m a -- | Return a 404 not found page. Also denotes no handler available. notFound :: MonadHandler m => m a -- | Return a 405 method not supported page. badMethod :: MonadHandler m => m a -- | Return a 401 status code notAuthenticated :: MonadHandler m => m a -- | Return a 403 permission denied page. permissionDenied :: MonadHandler m => Text -> m a -- | Return a 403 permission denied page. permissionDeniedI :: (RenderMessage (HandlerSite m) msg, MonadHandler m) => msg -> m a -- | Return a 400 invalid arguments page. invalidArgs :: MonadHandler m => [Text] -> m a -- | Return a 400 invalid arguments page. invalidArgsI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [msg] -> m a -- | Set the cookie on the client. setCookie :: MonadHandler m => SetCookie -> m () -- | Helper function for setCookieExpires value getExpires :: MonadIO m => Int -> m UTCTime -- | Unset the cookie on the client. -- -- Note: although the value used for key and path is Text, you -- should only use ASCII values to be HTTP compliant. deleteCookie :: MonadHandler m => Text -> Text -> m () -- | Set the language in the user session. Will show up in languages -- on the next request. setLanguage :: MonadHandler m => Text -> m () -- | Set attachment file name. -- -- Allows Unicode characters by encoding to UTF-8. Some modurn browser -- parse UTF-8 characters with out encoding setting. But, for example IE9 -- can't parse UTF-8 characters. This function use RFC 6266(RFC -- 5987) addContentDispositionFileName :: MonadHandler m => Text -> m () -- | Set an arbitrary response header. -- -- Note that, while the data type used here is Text, you must -- provide only ASCII value to be HTTP compliant. addHeader :: MonadHandler m => Text -> Text -> m () -- | Replace an existing header with a new value or add a new header if not -- present. -- -- Note that, while the data type used here is Text, you must -- provide only ASCII value to be HTTP compliant. replaceOrAddHeader :: MonadHandler m => Text -> Text -> m () -- | Set the Cache-Control header to indicate this response should be -- cached for the given number of seconds. cacheSeconds :: MonadHandler m => Int -> m () -- | Set the Expires header to some date in 2037. In other words, this -- content is never (realistically) expired. neverExpires :: MonadHandler m => m () -- | Set an Expires header in the past, meaning this content should not be -- cached. alreadyExpired :: MonadHandler m => m () -- | Set an Expires header to the given date. expiresAt :: MonadHandler m => UTCTime -> m () -- | Check the if-none-match header and, if it matches the given value, -- return a 304 not modified response. Otherwise, set the etag header to -- the given value. -- -- Note that it is the responsibility of the caller to ensure that the -- provided value is a valid etag value, no sanity checking is performed -- by this function. setEtag :: MonadHandler m => Text -> m () -- | Check the if-none-match header and, if it matches the given value, -- return a 304 not modified response. Otherwise, set the etag header to -- the given value. -- -- A weak etag is only expected to be semantically identical to the prior -- content, but doesn't have to be byte-for-byte identical. Therefore it -- can be useful for dynamically generated content that may be difficult -- to perform bytewise hashing upon. -- -- Note that it is the responsibility of the caller to ensure that the -- provided value is a valid etag value, no sanity checking is performed -- by this function. setWeakEtag :: MonadHandler m => Text -> m () -- | Set a variable in the user's session. -- -- The session is handled by the clientsession package: it sets an -- encrypted and hashed cookie on the client. This ensures that all data -- is secure and not tampered with. setSession :: MonadHandler m => Text -> Text -> m () -- | Same as setSession, but uses binary data for the value. setSessionBS :: MonadHandler m => Text -> ByteString -> m () -- | Unsets a session variable. See setSession. deleteSession :: MonadHandler m => Text -> m () -- | Clear all session variables. -- -- @since: 1.0.1 clearSession :: MonadHandler m => m () -- | Lookup for session data. lookupSession :: MonadHandler m => Text -> m (Maybe Text) -- | Lookup for session data in binary format. lookupSessionBS :: MonadHandler m => Text -> m (Maybe ByteString) -- | Get all session variables. getSession :: MonadHandler m => m SessionMap -- | Get a unique identifier. newIdent :: MonadHandler m => m Text -- | Redirect to a POST resource. -- -- This is not technically a redirect; instead, it returns an HTML page -- with a POST form, and some Javascript to automatically submit the -- form. This can be useful when you need to post a plain link somewhere -- that needs to cause changes on the server. redirectToPost :: (MonadHandler m, RedirectUrl (HandlerSite m) url) => url -> m a -- | Wraps the Content generated by hamletToContent in a -- RepHtml. hamletToRepHtml :: MonadHandler m => HtmlUrl (Route (HandlerSite m)) -> m Html -- | Deprecated synonym for withUrlRenderer. giveUrlRenderer :: MonadHandler m => ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output) -> m output -- | Provide a URL rendering function to the given function and return the -- result. Useful for processing Shakespearean templates. withUrlRenderer :: MonadHandler m => ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output) -> m output -- | Get the request's Request value. waiRequest :: MonadHandler m => m Request getMessageRender :: (MonadHandler m, RenderMessage (HandlerSite m) message) => m (message -> Text) -- | Use a per-request cache to avoid performing the same action multiple -- times. Values are stored by their type, the result of typeOf from -- Typeable. Therefore, you should use different newtype wrappers at each -- cache site. -- -- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth -- and exports functions that utilize it such as maybeAuth. This means -- that another module can create its own newtype wrapper to cache the -- same type from a different action without any cache conflicts. -- -- See the original announcement: -- http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals cached :: (MonadHandler m, Typeable a) => m a -> m a -- | Retrieves a value from the cache used by cached. cacheGet :: (MonadHandler m, Typeable a) => m (Maybe a) -- | Sets a value in the cache used by cached. cacheSet :: (MonadHandler m, Typeable a) => a -> m () -- | a per-request cache. just like cached. cached can only -- cache a single value per type. cachedBy stores multiple values -- per type by usage of a ByteString key -- -- cached is ideal to cache an action that has only one value of a -- type, such as the session's current user cachedBy is required -- if the action has parameters and can return multiple values per type. -- You can turn those parameters into a ByteString cache key. For -- example, caching a lookup of a Link by a token where multiple token -- lookups might be performed. cachedBy :: (MonadHandler m, Typeable a) => ByteString -> m a -> m a -- | Retrieves a value from the cache used by cachedBy. cacheByGet :: (MonadHandler m, Typeable a) => ByteString -> m (Maybe a) -- | Sets a value in the cache used by cachedBy. cacheBySet :: (MonadHandler m, Typeable a) => ByteString -> a -> m () -- | Get the list of supported languages supplied by the user. -- -- Languages are determined based on the following (in descending order -- of preference): -- -- -- -- Yesod will seek the first language from the returned list matched with -- languages supporting by your application. This language will be used -- to render i18n templates. If a matching language is not found the -- default language will be used. -- -- This is handled by parseWaiRequest (not exposed). -- -- NOTE: Before version 1.6.19.0, this function -- prioritized the session variable above all other sources. languages :: MonadHandler m => m [Text] -- | Lookup a request header. lookupHeader :: MonadHandler m => CI ByteString -> m (Maybe ByteString) -- | Lookup a request header. lookupHeaders :: MonadHandler m => CI ByteString -> m [ByteString] -- | Lookup basic authentication data from Authorization header of -- request. Returns user name and password lookupBasicAuth :: MonadHandler m => m (Maybe (Text, Text)) -- | Lookup bearer authentication datafrom Authorization header of -- request. Returns bearer token value lookupBearerAuth :: MonadHandler m => m (Maybe Text) -- | Lookup for GET parameters. lookupGetParams :: MonadHandler m => Text -> m [Text] -- | Lookup for GET parameters. lookupGetParam :: MonadHandler m => Text -> m (Maybe Text) -- | Lookup for POST parameters. lookupPostParams :: (MonadResource m, MonadHandler m) => Text -> m [Text] lookupPostParam :: (MonadResource m, MonadHandler m) => Text -> m (Maybe Text) -- | Lookup for POSTed files. lookupFile :: MonadHandler m => Text -> m (Maybe FileInfo) -- | Lookup for POSTed files. lookupFiles :: MonadHandler m => Text -> m [FileInfo] -- | Lookup for cookie data. lookupCookie :: MonadHandler m => Text -> m (Maybe Text) -- | Lookup for cookie data. lookupCookies :: MonadHandler m => Text -> m [Text] -- | Select a representation to send to the client based on the -- representations provided inside this do-block. Should be used together -- with provideRep. selectRep :: MonadHandler m => Writer (Endo [ProvidedRep m]) () -> m TypedContent -- | Provide a single representation to be used, based on the request of -- the client. Should be used together with selectRep. provideRep :: (Monad m, HasContentType a) => m a -> Writer (Endo [ProvidedRep m]) () -- | Same as provideRep, but instead of determining the content type -- from the type of the value itself, you provide the content type -- separately. This can be a convenience instead of creating newtype -- wrappers for uncommonly used content types. -- --
--   provideRepType "application/x-special-format" "This is the content"
--   
provideRepType :: (Monad m, ToContent a) => ContentType -> m a -> Writer (Endo [ProvidedRep m]) () -- | Stream in the raw request body without any parsing. rawRequestBody :: forall (m :: Type -> Type) i. MonadHandler m => ConduitT i ByteString m () -- | Stream the data from the file. Since Yesod 1.2, this has been -- generalized to work in any MonadResource. fileSource :: forall (m :: Type -> Type). MonadResource m => FileInfo -> ConduitT () ByteString m () -- | Extract a strict ByteString body from a FileInfo. -- -- This function will block while reading the file. -- --
--   do
--       fileByteString <- fileSourceByteString fileInfo
--   
fileSourceByteString :: MonadResource m => FileInfo -> m ByteString -- | Provide a pure value for the response body. -- --
--   respond ct = return . TypedContent ct . toContent
--   
respond :: (Monad m, ToContent a) => ContentType -> a -> m TypedContent -- | Use a Source for the response body. -- -- Note that, for ease of use, the underlying monad is a -- HandlerFor. This implies that you can run any -- HandlerFor action. However, since a streaming response occurs -- after the response headers have already been sent, some actions make -- no sense here. For example: short-circuit responses, setting headers, -- changing status codes, etc. respondSource :: ContentType -> ConduitT () (Flush Builder) (HandlerFor site) () -> HandlerFor site TypedContent -- | In a streaming response, send a single chunk of data. This function -- works on most datatypes, such as ByteString and -- Html. sendChunk :: forall (m :: Type -> Type) a i. (Monad m, ToFlushBuilder a) => a -> ConduitT i (Flush Builder) m () -- | In a streaming response, send a flush command, causing all buffered -- data to be immediately sent to the client. sendFlush :: forall (m :: Type -> Type) i. Monad m => ConduitT i (Flush Builder) m () -- | Type-specialized version of sendChunk for strict -- ByteStrings. sendChunkBS :: forall (m :: Type -> Type) i. Monad m => ByteString -> ConduitT i (Flush Builder) m () -- | Type-specialized version of sendChunk for lazy -- ByteStrings. sendChunkLBS :: forall (m :: Type -> Type) i. Monad m => ByteString -> ConduitT i (Flush Builder) m () -- | Type-specialized version of sendChunk for strict -- Texts. sendChunkText :: forall (m :: Type -> Type) i. Monad m => Text -> ConduitT i (Flush Builder) m () -- | Type-specialized version of sendChunk for lazy Texts. sendChunkLazyText :: forall (m :: Type -> Type) i. Monad m => Text -> ConduitT i (Flush Builder) m () -- | Type-specialized version of sendChunk for Htmls. sendChunkHtml :: forall (m :: Type -> Type) i. Monad m => Html -> ConduitT i (Flush Builder) m () -- | The default cookie name for the CSRF token ("XSRF-TOKEN"). defaultCsrfCookieName :: ByteString -- | Sets a cookie with a CSRF token, using defaultCsrfCookieName -- for the cookie name. -- -- The cookie's path is set to /, making it valid for your whole -- website. setCsrfCookie :: MonadHandler m => m () -- | Takes a SetCookie and overrides its value with a CSRF token, -- then sets the cookie. -- -- Make sure to set the setCookiePath to the root path of your -- application, otherwise you'll generate a new CSRF token for every path -- of your app. If your app is run from from e.g. www.example.com/app1, -- use app1. The vast majority of sites will just use -- /. setCsrfCookieWithCookie :: MonadHandler m => SetCookie -> m () -- | The default header name for the CSRF token ("X-XSRF-TOKEN"). defaultCsrfHeaderName :: CI ByteString -- | Takes a header name to lookup a CSRF token. If the value doesn't match -- the token stored in the session, this function throws a -- PermissionDenied error. checkCsrfHeaderNamed :: MonadHandler m => CI ByteString -> m () -- | Takes a header name to lookup a CSRF token, and returns whether the -- value matches the token stored in the session. hasValidCsrfHeaderNamed :: MonadHandler m => CI ByteString -> m Bool -- | The default parameter name for the CSRF token ("_token") defaultCsrfParamName :: Text -- | Takes a POST parameter name to lookup a CSRF token. If the value -- doesn't match the token stored in the session, this function throws a -- PermissionDenied error. checkCsrfParamNamed :: MonadHandler m => Text -> m () -- | Takes a POST parameter name to lookup a CSRF token, and returns -- whether the value matches the token stored in the session. hasValidCsrfParamNamed :: MonadHandler m => Text -> m Bool -- | Checks that a valid CSRF token is present in either the request -- headers or POST parameters. If the value doesn't match the token -- stored in the session, this function throws a PermissionDenied -- error. checkCsrfHeaderOrParam :: (MonadHandler m, MonadLogger m) => CI ByteString -> Text -> m () getSubYesod :: MonadHandler m => m (SubHandlerSite m) getRouteToParent :: MonadHandler m => m (Route (SubHandlerSite m) -> Route (HandlerSite m)) getSubCurrentRoute :: MonadHandler m => m (Maybe (Route (SubHandlerSite m))) -- | Set the localised page title. -- -- n.b. See comments for setTitle setTitleI :: (MonadWidget m, RenderMessage (HandlerSite m) msg) => msg -> m () -- | Add description meta tag to the head of the page -- -- Google does not use the description tag as a ranking signal, but the -- contents of this tag will likely affect your click-through rate since -- it shows up in search results. -- -- The average length of the description shown in Google's search results -- is about 160 characters on desktop, and about 130 characters on -- mobile, at time of writing. -- -- Source: -- https://www.advancedwebranking.com/blog/meta-tags-important-in-seo/ setDescription :: MonadWidget m => Text -> m () -- | Add translated description meta tag to the head of the page -- -- n.b. See comments for setDescription. setDescriptionI :: (MonadWidget m, RenderMessage (HandlerSite m) msg) => msg -> m () -- | Add description meta tag to the head of the page -- -- Google does not use the description tag as a ranking signal, but the -- contents of this tag will likely affect your click-through rate since -- it shows up in search results. -- -- The average length of the description shown in Google's search results -- is about 160 characters on desktop, and about 130 characters on -- mobile, at time of writing. -- -- Unlike setDescription, this version is *idempotent* - calling -- it multiple times will result in only a single description meta tag in -- the head. -- -- Source: -- https://www.advancedwebranking.com/blog/meta-tags-important-in-seo/ setDescriptionIdemp :: MonadWidget m => Text -> m () -- | Add translated description meta tag to the head of the page -- -- n.b. See comments for setDescriptionIdemp. -- -- Unlike setDescriptionI, this version is *idempotent* - calling -- it multiple times will result in only a single description meta tag in -- the head. setDescriptionIdempI :: (MonadWidget m, RenderMessage (HandlerSite m) msg) => msg -> m () -- | Add OpenGraph type meta tag to the head of the page -- -- See all available OG types here: https://ogp.me/#types setOGType :: MonadWidget m => Text -> m () -- | Add OpenGraph image meta tag to the head of the page -- -- Best practices: -- -- -- -- Source: https://ahrefs.com/blog/open-graph-meta-tags/ setOGImage :: MonadWidget m => Text -> m () -- | Link to the specified local stylesheet. addStylesheet :: MonadWidget m => Route (HandlerSite m) -> m () -- | Link to the specified local stylesheet. addStylesheetAttrs :: MonadWidget m => Route (HandlerSite m) -> [(Text, Text)] -> m () -- | Link to the specified remote stylesheet. addStylesheetRemote :: MonadWidget m => Text -> m () -- | Link to the specified remote stylesheet. addStylesheetRemoteAttrs :: MonadWidget m => Text -> [(Text, Text)] -> m () addStylesheetEither :: MonadWidget m => Either (Route (HandlerSite m)) Text -> m () addScriptEither :: MonadWidget m => Either (Route (HandlerSite m)) Text -> m () -- | Link to the specified local script. addScript :: MonadWidget m => Route (HandlerSite m) -> m () -- | Link to the specified local script. addScriptAttrs :: MonadWidget m => Route (HandlerSite m) -> [(Text, Text)] -> m () -- | Link to the specified remote script. addScriptRemote :: MonadWidget m => Text -> m () -- | Link to the specified remote script. addScriptRemoteAttrs :: MonadWidget m => Text -> [(Text, Text)] -> m () whamlet :: QuasiQuoter whamletFile :: FilePath -> Q Exp whamletFileWithSettings :: HamletSettings -> FilePath -> Q Exp asWidgetT :: forall site (m :: Type -> Type). WidgetT site m () -> WidgetT site m () -- | Wraps the Content generated by hamletToContent in a -- RepHtml. ihamletToRepHtml :: (MonadHandler m, RenderMessage (HandlerSite m) message) => HtmlUrlI18n message (Route (HandlerSite m)) -> m Html -- | Wraps the Content generated by hamletToContent in a -- RepHtml. -- -- Since 1.2.1 ihamletToHtml :: (MonadHandler m, RenderMessage (HandlerSite m) message) => HtmlUrlI18n message (Route (HandlerSite m)) -> m Html handlerToWidget :: HandlerFor site a -> WidgetFor site a -- | Default implementation of makeLogger. Sends to stdout and -- automatically flushes on each write. -- -- Since 1.4.10 defaultMakeLogger :: IO Logger -- | Default implementation of messageLoggerSource. Checks if the -- message should be logged using the provided function, and if so, -- formats using formatLogMessage. You can use -- defaultShouldLogIO as the provided function. -- -- Since 1.4.10 defaultMessageLoggerSource :: (LogSource -> LogLevel -> IO Bool) -> Logger -> Loc -> LogSource -> LogLevel -> LogStr -> IO () -- | Default implementation of shouldLog. Logs everything at or -- above LevelInfo. -- -- Since 1.4.10 defaultShouldLogIO :: LogSource -> LogLevel -> IO Bool -- | Default implementation of yesodMiddleware. Adds the response -- header "Vary: Accept, Accept-Language", "X-XSS-Protection: 1; -- mode=block", and performs authorization checks. -- -- Since 1.2.0 defaultYesodMiddleware :: Yesod site => HandlerFor site res -> HandlerFor site res -- | Defends against session hijacking by setting the secure bit on session -- cookies so that browsers will not transmit them over http. With this -- setting on, it follows that the server will regard requests made over -- http as sessionless, because the session cookie will not be included -- in the request. Use this as part of a total security measure which -- also includes disabling HTTP traffic to the site or issuing redirects -- from HTTP urls, and composing sslOnlyMiddleware with the site's -- yesodMiddleware. -- -- Since 1.4.7 sslOnlySessions :: IO (Maybe SessionBackend) -> IO (Maybe SessionBackend) -- | Helps defend against CSRF attacks by setting the SameSite attribute on -- session cookies to Lax. With the Lax setting, the cookie will be sent -- with same-site requests, and with cross-site top-level navigations. -- -- This option is liable to change in future versions of Yesod as the -- spec evolves. View more information here. laxSameSiteSessions :: IO (Maybe SessionBackend) -> IO (Maybe SessionBackend) -- | Helps defend against CSRF attacks by setting the SameSite attribute on -- session cookies to Strict. With the Strict setting, the cookie will -- only be sent with same-site requests. -- -- This option is liable to change in future versions of Yesod as the -- spec evolves. View more information here. strictSameSiteSessions :: IO (Maybe SessionBackend) -> IO (Maybe SessionBackend) -- | Apply a Strict-Transport-Security header with the specified timeout to -- all responses so that browsers will rewrite all http links to https -- until the timeout expires. For security, the max-age of the STS header -- should always equal or exceed the client sessions timeout. This -- defends against SSL-stripping man-in-the-middle attacks. It is only -- effective if a secure connection has already been made; -- Strict-Transport-Security headers are ignored over HTTP. -- -- Since 1.4.7 sslOnlyMiddleware :: Int -> HandlerFor site res -> HandlerFor site res -- | Check if a given request is authorized via isAuthorized and -- isWriteRequest. -- -- Since 1.2.0 authorizationCheck :: Yesod site => HandlerFor site () -- | Calls csrfCheckMiddleware with isWriteRequest, -- defaultCsrfHeaderName, and defaultCsrfParamName as -- parameters. -- -- Since 1.4.14 defaultCsrfCheckMiddleware :: Yesod site => HandlerFor site res -> HandlerFor site res -- | Looks up the CSRF token from the request headers or POST parameters. -- If the value doesn't match the token stored in the session, this -- function throws a PermissionDenied error. -- -- For details, see the "AJAX CSRF protection" section of -- Yesod.Core.Handler. -- -- Since 1.4.14 csrfCheckMiddleware :: HandlerFor site res -> HandlerFor site Bool -> CI ByteString -> Text -> HandlerFor site res -- | Calls csrfSetCookieMiddleware with the -- defaultCsrfCookieName. -- -- The cookie's path is set to /, making it valid for your whole -- website. -- -- Since 1.4.14 defaultCsrfSetCookieMiddleware :: HandlerFor site res -> HandlerFor site res -- | Takes a SetCookie and overrides its value with a CSRF token, -- then sets the cookie. See setCsrfCookieWithCookie. -- -- For details, see the "AJAX CSRF protection" section of -- Yesod.Core.Handler. -- -- Make sure to set the setCookiePath to the root path of your -- application, otherwise you'll generate a new CSRF token for every path -- of your app. If your app is run from from e.g. www.example.com/app1, -- use app1. The vast majority of sites will just use -- /. -- -- Since 1.4.14 csrfSetCookieMiddleware :: HandlerFor site res -> SetCookie -> HandlerFor site res -- | Calls defaultCsrfSetCookieMiddleware and -- defaultCsrfCheckMiddleware. -- -- For details, see the "AJAX CSRF protection" section of -- Yesod.Core.Handler. -- -- You can chain this middleware together with other middleware like so: -- --
--   yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware
--   
-- -- or: -- --
--   yesodMiddleware app = defaultYesodMiddleware $ defaultCsrfMiddleware $ app
--   
-- -- Since 1.4.14 defaultCsrfMiddleware :: Yesod site => HandlerFor site res -> HandlerFor site res -- | Convert a widget to a PageContent. widgetToPageContent :: Yesod site => WidgetFor site () -> HandlerFor site (PageContent (Route site)) -- | The default error handler for errorHandler. defaultErrorHandler :: Yesod site => ErrorResponse -> HandlerFor site TypedContent -- | Default formatting for log messages. When you use the template haskell -- logging functions for to log with information about the source -- location, that information will be appended to the end of the log. -- When you use the non-TH logging functions, like logDebugN, -- this function does not include source information. This currently -- works by checking to see if the package name is the string -- "<unknown>". This is a hack, but it removes some of the visual -- clutter from non-TH logs. -- -- Since 1.4.10 formatLogMessage :: IO ZonedDate -> Loc -> LogSource -> LogLevel -> LogStr -> IO LogStr -- | Customize the cookies used by the session backend. You may use this -- function on your definition of makeSessionBackend. -- -- For example, you could set the cookie domain so that it would work -- across many subdomains: -- --
--   makeSessionBackend site =
--       (fmap . fmap) (customizeSessionCookies addDomain) ...
--     where
--       addDomain cookie = cookie { setCookieDomain = Just ".example.com" }
--   
-- -- Default: Do not customize anything (id). customizeSessionCookies :: (SetCookie -> SetCookie) -> SessionBackend -> SessionBackend defaultClientSessionBackend :: Int -> FilePath -> IO SessionBackend -- | Create a SessionBackend which reads the session key from the -- named environment variable. -- -- This can be useful if: -- --
    --
  1. You can't rely on a persistent file system (e.g. Heroku)
  2. --
  3. Your application is open source (e.g. you can't commit the -- key)
  4. --
-- -- By keeping a consistent value in the environment variable, your users -- will have consistent sessions without relying on the file system. -- -- Note: A suitable value should only be obtained in one of two ways: -- --
    --
  1. Run this code without the variable set, a value will be generated -- and printed on devstdout/
  2. --
  3. Use clientsession-generate
  4. --
-- -- Since 1.4.5 envClientSessionBackend :: Int -> String -> IO SessionBackend clientSessionBackend :: Key -> IO ClientSessionDateCache -> SessionBackend loadClientSession :: Key -> IO ClientSessionDateCache -> ByteString -> Request -> IO (SessionMap, SaveSession) -- | Guess the approot based on request headers, with fall back to the -- specified AppRoot. -- -- Since 1.4.16 guessApprootOr :: Approot site -> Approot site -- | Get the textual application root from an Approot value. -- -- Since 1.4.17 getApprootText :: Approot site -> site -> Request -> Text -- | Provide both an HTML and JSON representation for a piece of data, -- using the default layout for the HTML output (defaultLayout). defaultLayoutJson :: (Yesod site, ToJSON a) => WidgetFor site () -> HandlerFor site a -> HandlerFor site TypedContent -- | Wraps a data type in a RepJson. The data type must support -- conversion to JSON via ToJSON. jsonToRepJson :: (Monad m, ToJSON a) => a -> m Value -- | Convert a value to a JSON representation via aeson's toJSON -- function. returnJson :: (Monad m, ToJSON a) => a -> m Value -- | Convert a value to a JSON representation via aeson's toEncoding -- function. returnJsonEncoding :: (Monad m, ToJSON a) => a -> m Encoding -- | Provide a JSON representation for usage with selectReps, -- using aeson's toJSON (aeson >= 0.11: toEncoding) -- function to perform the conversion. provideJson :: forall (m :: Type -> Type) a. (Monad m, ToJSON a) => a -> Writer (Endo [ProvidedRep m]) () -- | Same as parseInsecureJsonBody parseJsonBody :: (MonadHandler m, FromJSON a) => m (Result a) -- | Same as parseCheckJsonBody, but does not check that the mime -- type indicates JSON content. -- -- Note: This function is vulnerable to CSRF attacks. parseInsecureJsonBody :: (MonadHandler m, FromJSON a) => m (Result a) -- | Parse the request body to a data type as a JSON value. The data type -- must support conversion from JSON via FromJSON. If you want the -- raw JSON value, just ask for a Result Value. -- -- The MIME type must indicate JSON content. Requiring a JSON -- content-type helps secure your site against CSRF attacks (browsers -- will perform POST requests for form and text/plain content-types -- without doing a CORS check, and those content-types can easily contain -- valid JSON). -- -- Note that this function will consume the request body. As such, -- calling it twice will result in a parse error on the second call, -- since the request body will no longer be available. parseCheckJsonBody :: (MonadHandler m, FromJSON a) => m (Result a) -- | Same as parseInsecureJsonBody, but return an invalid args -- response on a parse error. parseJsonBody_ :: (MonadHandler m, FromJSON a) => m a -- | Same as parseInsecureJsonBody, but return an invalid args -- response on a parse error. requireJsonBody :: (MonadHandler m, FromJSON a) => m a -- | Same as parseInsecureJsonBody, but return an invalid args -- response on a parse error. requireInsecureJsonBody :: (MonadHandler m, FromJSON a) => m a -- | Same as parseCheckJsonBody, but return an invalid args response -- on a parse error. requireCheckJsonBody :: (MonadHandler m, FromJSON a) => m a -- | jsonOrRedirect simplifies the scenario where a POST handler sends a -- different response based on Accept headers: -- --
    --
  1. 200 with JSON data if the client prefers application/json -- (e.g. AJAX, see acceptsJSON).
  2. --
  3. 3xx otherwise, following the PRG pattern.
  4. --
jsonOrRedirect :: (MonadHandler m, ToJSON a) => Route (HandlerSite m) -> a -> m Value -- | jsonEncodingOrRedirect simplifies the scenario where a POST handler -- sends a different response based on Accept headers: -- --
    --
  1. 200 with JSON data if the client prefers application/json -- (e.g. AJAX, see acceptsJSON).
  2. --
  3. 3xx otherwise, following the PRG pattern. @since 1.4.21
  4. --
jsonEncodingOrRedirect :: (MonadHandler m, ToJSON a) => Route (HandlerSite m) -> a -> m Encoding -- | Returns True if the client prefers application/json -- as indicated by the Accept HTTP header. acceptsJson :: MonadHandler m => m Bool -- | Given the Content-Type header, returns if it is JSON. -- -- This function is currently a simple check for -- application/json, but in the future may check for alternative -- representations such as xxx/yyy+json. contentTypeHeaderIsJson :: ByteString -> Bool runFakeHandler :: (Yesod site, MonadIO m) => SessionMap -> (site -> Logger) -> site -> HandlerT site IO a -> m (Either ErrorResponse a) yesodRunner :: (ToTypedContent res, Yesod site) => HandlerFor site res -> YesodRunnerEnv site -> Maybe (Route site) -> Application yesodRender :: Yesod y => y -> ResolvedApproot -> Route y -> [(Text, Text)] -> Text liteApp :: Writer LiteApp () -> LiteApp dispatchTo :: ToTypedContent a => LiteHandler a -> Writer LiteApp () onMethod :: Method -> Writer LiteApp () -> Writer LiteApp () onStatic :: Text -> Writer LiteApp () -> Writer LiteApp () withDynamic :: PathPiece p => (p -> Writer LiteApp ()) -> Writer LiteApp () withDynamicMulti :: PathMultiPiece ps => (ps -> Writer LiteApp ()) -> Writer LiteApp () -- | Gets the title of the current page and the hierarchy of parent pages, -- along with their respective titles. breadcrumbs :: (YesodBreadcrumbs site, Show (Route site), Eq (Route site)) => HandlerFor site (Text, [(Route site, Text)]) -- | Default options for generating routes. -- -- Defaults to all instances derived. defaultOpts :: RouteOpts setEqDerived :: Bool -> RouteOpts -> RouteOpts setShowDerived :: Bool -> RouteOpts -> RouteOpts setReadDerived :: Bool -> RouteOpts -> RouteOpts -- | A quasi-quoter to parse a string into a list of Resources. -- Checks for overlapping routes, failing if present; use -- parseRoutesNoCheck to skip the checking. See documentation site -- for details on syntax. parseRoutes :: QuasiQuoter -- | Same as parseRoutes, but uses an external file instead of -- quasiquotation. -- -- The recommended file extension is .yesodroutes. parseRoutesFile :: FilePath -> Q Exp -- | Same as parseRoutesNoCheck, but uses an external file instead -- of quasiquotation. -- -- The recommended file extension is .yesodroutes. parseRoutesFileNoCheck :: FilePath -> Q Exp -- | Same as parseRoutes, but performs no overlap checking. parseRoutesNoCheck :: QuasiQuoter -- | Generates URL datatype and site function for the given -- Resources. This is used for creating sites, not -- subsites. See mkYesodSubData and mkYesodSubDispatch for -- the latter. Use parseRoutes to create the Resources. -- -- Contexts and type variables in the name of the datatype are parsed. -- For example, a datatype App a with typeclass constraint -- MyClass a can be written as "(MyClass a) => App -- a". mkYesod :: String -> [ResourceTree String] -> Q [Dec] -- | mkYesod but with custom options. mkYesodOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec] -- | Similar to mkYesod, except contexts and type variables are not -- parsed. Instead, they are explicitly provided. You can write -- (MyClass a) => App a with mkYesodWith -- [["MyClass","a"]] "App" ["a"] .... mkYesodWith :: [[String]] -> String -> [String] -> [ResourceTree String] -> Q [Dec] -- | Sometimes, you will want to declare your routes in one file and define -- your handlers elsewhere. For example, this is the only way to break up -- a monolithic file into smaller parts. Use this function, paired with -- mkYesodDispatch, to do just that. mkYesodData :: String -> [ResourceTree String] -> Q [Dec] -- | mkYesodData but with custom options. mkYesodDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec] mkYesodSubData :: String -> [ResourceTree String] -> Q [Dec] mkYesodSubDataOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec] -- | See mkYesodData. mkYesodDispatch :: String -> [ResourceTree String] -> Q [Dec] -- | See mkYesodDataOpts mkYesodDispatchOpts :: RouteOpts -> String -> [ResourceTree String] -> Q [Dec] mkYesodSubDispatch :: [ResourceTree a] -> Q Exp -- | Convert the given argument into a WAI application, executable with any -- WAI handler. This function will provide no middlewares; if you want -- commonly used middlewares, please use toWaiApp. toWaiAppPlain :: YesodDispatch site => site -> IO Application -- | Generate a random number uniformly distributed in the full range of -- Int. -- -- Note: Before 1.6.20, this generates pseudo-random number in an -- unspecified range. The range size may not be a power of 2. Since -- 1.6.20, this uses a secure entropy source and generates in the full -- range of Int. defaultGen :: IO Int -- | Pure low level function to construct WAI application. Usefull when you -- need not standard way to run your app, or want to embed it inside -- another app. toWaiAppYre :: YesodDispatch site => YesodRunnerEnv site -> Application -- | Same as toWaiAppPlain, but provides a default set of -- middlewares. This set may change with future releases, but currently -- covers: -- -- toWaiApp :: YesodDispatch site => site -> IO Application -- | A default set of middlewares. -- -- Since 1.2.0 mkDefaultMiddlewares :: Logger -> IO Middleware -- | All of the default middlewares, excluding logging. -- -- Since 1.2.12 defaultMiddlewaresNoLogging :: Middleware -- | Deprecated synonym for warp. warpDebug :: YesodDispatch site => Int -> site -> IO () -- | Runs your application using default middlewares (i.e., via -- toWaiApp). It reads port information from the PORT environment -- variable, as used by tools such as Keter and the FP Complete School of -- Haskell. -- -- Note that the exact behavior of this function may be modified slightly -- over time to work correctly with external tools, without a change to -- the type signature. warpEnv :: YesodDispatch site => site -> IO () -- | Default constructor for yreGetMaxExpires field. Low level -- function for simple manual construction of YesodRunnerEnv. getGetMaxExpires :: IO (IO Text) -- | Return an Unauthorized value, with the given i18n message. unauthorizedI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => msg -> m AuthResult yesodVersion :: String -- | Return the same URL if the user is authorized to see it. -- -- Built on top of isAuthorized. This is useful for building page -- that only contain links to pages the user is allowed to see. maybeAuthorized :: Yesod site => Route site -> Bool -> HandlerT site IO (Maybe (Route site)) showIntegral :: Integral a => a -> String check :: forall (m :: Type -> Type) msg a. (Monad m, RenderMessage (HandlerSite m) msg) => (a -> Either msg a) -> Field m a -> Field m a -- | Promote a Field into a FormInput, requiring that the -- value be present and valid. ireq :: forall (m :: Type -> Type) a. (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m a -> Text -> FormInput m a -- | Promote a Field into a FormInput, with its presence -- being optional. If the value is present but does not parse correctly, -- the form will still fail. iopt :: forall (m :: Type -> Type) a. Monad m => Field m a -> Text -> FormInput m (Maybe a) -- | Run a FormInput on the GET parameters (i.e., query string). -- If parsing fails, calls invalidArgs. runInputGet :: MonadHandler m => FormInput m a -> m a -- | Run a FormInput on the GET parameters (i.e., query string). -- Does not throw exceptions on failure. -- -- Since 1.4.1 runInputGetResult :: MonadHandler m => FormInput m a -> m (FormResult a) -- | Run a FormInput on the POST parameters (i.e., request body). -- If parsing fails, calls invalidArgs. runInputPost :: MonadHandler m => FormInput m a -> m a -- | Run a FormInput on the POST parameters (i.e., request body). -- Does not throw exceptions on failure. runInputPostResult :: MonadHandler m => FormInput m a -> m (FormResult a) -- | Get a unique identifier. newFormIdent :: forall (m :: Type -> Type). Monad m => MForm m Text formToAForm :: forall (m :: Type -> Type) site a. (HandlerSite m ~ site, Monad m) => MForm m (FormResult a, [FieldView site]) -> AForm m a aFormToForm :: forall (m :: Type -> Type) site a. (Monad m, HandlerSite m ~ site) => AForm m a -> MForm m (FormResult a, [FieldView site] -> [FieldView site]) askParams :: forall (m :: Type -> Type). Monad m => MForm m (Maybe Env) askFiles :: forall (m :: Type -> Type). Monad m => MForm m (Maybe FileEnv) -- | Converts a form field into monadic form WForm. This field -- requires a value and will return FormFailure if left empty. wreq :: forall site (m :: Type -> Type) a. (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> Maybe a -> WForm m (FormResult a) -- | Same as wreq but with your own message to be rendered in case -- the value is not provided. -- -- This is useful when you have several required fields on the page and -- you want to differentiate between which fields were left blank. -- Otherwise the user sees "Value is required" multiple times, which is -- ambiguous. wreqMsg :: forall site msg (m :: Type -> Type) a. (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> msg -> Maybe a -> WForm m (FormResult a) -- | Converts a form field into monadic form WForm. This field is -- optional, i.e. if filled in, it returns 'Just a', if left empty, it -- returns Nothing. Arguments are the same as for wreq -- (apart from type of default value). wopt :: forall (m :: Type -> Type) site a. (MonadHandler m, HandlerSite m ~ site) => Field m a -> FieldSettings site -> Maybe (Maybe a) -> WForm m (FormResult (Maybe a)) -- | Converts a monadic form WForm into an applicative form -- AForm. wFormToAForm :: forall (m :: Type -> Type) a. MonadHandler m => WForm m (FormResult a) -> AForm m a -- | Converts a monadic form WForm into another monadic form -- MForm. wFormToMForm :: forall (m :: Type -> Type) site a. (MonadHandler m, HandlerSite m ~ site) => WForm m a -> MForm m (a, [FieldView site]) -- | Converts a monadic form MForm into another monadic form -- WForm. mFormToWForm :: forall (m :: Type -> Type) site a. (MonadHandler m, HandlerSite m ~ site) => MForm m (a, FieldView site) -> WForm m a -- | Converts a form field into monadic form. This field requires a value -- and will return FormFailure if left empty. mreq :: forall site (m :: Type -> Type) a. (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> Maybe a -> MForm m (FormResult a, FieldView site) -- | Same as mreq but with your own message to be rendered in case -- the value is not provided. -- -- This is useful when you have several required fields on the page and -- you want to differentiate between which fields were left blank. -- Otherwise the user sees "Value is required" multiple times, which is -- ambiguous. mreqMsg :: forall site msg (m :: Type -> Type) a. (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> msg -> Maybe a -> MForm m (FormResult a, FieldView site) -- | Converts a form field into monadic form. This field is optional, i.e. -- if filled in, it returns 'Just a', if left empty, it returns -- Nothing. Arguments are the same as for mreq (apart from -- type of default value). mopt :: forall site (m :: Type -> Type) a. (site ~ HandlerSite m, MonadHandler m) => Field m a -> FieldSettings site -> Maybe (Maybe a) -> MForm m (FormResult (Maybe a), FieldView site) -- | Applicative equivalent of mreq. areq :: forall site (m :: Type -> Type) a. (RenderMessage site FormMessage, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> Maybe a -> AForm m a -- | Same as areq but with your own message to be rendered in case -- the value is not provided. -- -- This is useful when you have several required fields on the page and -- you want to differentiate between which fields were left blank. -- Otherwise the user sees "Value is required" multiple times, which is -- ambiguous. areqMsg :: forall site msg (m :: Type -> Type) a. (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => Field m a -> FieldSettings site -> msg -> Maybe a -> AForm m a -- | Applicative equivalent of mopt. aopt :: forall (m :: Type -> Type) a. MonadHandler m => Field m a -> FieldSettings (HandlerSite m) -> Maybe (Maybe a) -> AForm m (Maybe a) -- | This function is used to both initially render a form and to later -- extract results from it. Note that, due to CSRF protection and a few -- other issues, forms submitted via GET and POST are slightly different. -- As such, be sure to call the relevant function based on how the form -- will be submitted, not the current request method. -- -- For example, a common case is displaying a form on a GET request and -- having the form submit to a POST page. In such a case, both the GET -- and POST handlers should use runFormPost. runFormPost :: (RenderMessage (HandlerSite m) FormMessage, MonadResource m, MonadHandler m) => (Markup -> MForm m (FormResult a, xml)) -> m ((FormResult a, xml), Enctype) -- | Similar to runFormPost, except it always ignores the currently -- available environment. This is necessary in cases like a wizard UI, -- where a single page will both receive and incoming form and produce a -- new, blank form. For general usage, you can stick with -- runFormPost. generateFormPost :: (RenderMessage (HandlerSite m) FormMessage, MonadHandler m) => (Markup -> MForm m (FormResult a, xml)) -> m (xml, Enctype) runFormPostNoToken :: MonadHandler m => (Markup -> MForm m a) -> m (a, Enctype) runFormGet :: MonadHandler m => (Markup -> MForm m a) -> m (a, Enctype) -- | Since 1.3.11 generateFormGet' :: MonadHandler m => (Markup -> MForm m (FormResult a, xml)) -> m (xml, Enctype) generateFormGet :: MonadHandler m => (Markup -> MForm m a) -> m (a, Enctype) -- | Creates a hidden field on the form that identifies it. This -- identification is then used to distinguish between missing and -- wrong form data when a single handler contains more than one -- form. -- -- For instance, if you have the following code on your handler: -- --
--   ((fooRes, fooWidget), fooEnctype) <- runFormPost fooForm
--   ((barRes, barWidget), barEnctype) <- runFormPost barForm
--   
-- -- Then replace it with -- --
--   ((fooRes, fooWidget), fooEnctype) <- runFormPost $ identifyForm "foo" fooForm
--   ((barRes, barWidget), barEnctype) <- runFormPost $ identifyForm "bar" barForm
--   
-- -- Note that it's your responsibility to ensure that the identification -- strings are unique (using the same one twice on a single handler will -- not generate any errors). This allows you to create a variable number -- of forms and still have them work even if their number or order change -- between the HTML generation and the form submission. identifyForm :: forall (m :: Type -> Type) a. Monad m => Text -> (Markup -> MForm m (FormResult a, WidgetFor (HandlerSite m) ())) -> Markup -> MForm m (FormResult a, WidgetFor (HandlerSite m) ()) -- | Render a form into a series of tr tags. Note that, in order to allow -- you to add extra rows to the table, this function does not wrap -- up the resulting HTML in a table tag; you must do that yourself. renderTable :: forall (m :: Type -> Type) a. Monad m => FormRender m a -- | render a field inside a div renderDivs :: forall (m :: Type -> Type) a. Monad m => FormRender m a -- | render a field inside a div, not displaying any label renderDivsNoLabels :: forall (m :: Type -> Type) a. Monad m => FormRender m a -- | Render a form using Bootstrap v2-friendly shamlet syntax. If you're -- using Bootstrap v3, then you should use the functions from module -- Yesod.Form.Bootstrap3. -- -- Sample Hamlet: -- --
--   <form .form-horizontal method=post action=@{ActionR} enctype=#{formEnctype}>
--     <fieldset>
--       <legend>_{MsgLegend}
--       $case result
--         $of FormFailure reasons
--           $forall reason <- reasons
--             <div .alert .alert-error>#{reason}
--         $of _
--       ^{formWidget}
--       <div .form-actions>
--         <input .btn .primary type=submit value=_{MsgSubmit}>
--   
-- -- Since 1.3.14 renderBootstrap2 :: forall (m :: Type -> Type) a. Monad m => FormRender m a -- | Deprecated synonym for renderBootstrap2. renderBootstrap :: forall (m :: Type -> Type) a. Monad m => FormRender m a -- | Return the given error message if the predicate is false. checkBool :: forall (m :: Type -> Type) msg a. (Monad m, RenderMessage (HandlerSite m) msg) => (a -> Bool) -> msg -> Field m a -> Field m a checkM :: (Monad m, RenderMessage (HandlerSite m) msg) => (a -> m (Either msg a)) -> Field m a -> Field m a -- | Same as checkM, but modifies the datatype. -- -- In order to make this work, you must provide a function to convert -- back from the new datatype to the old one (the second argument to this -- function). -- -- Since 1.1.2 checkMMap :: (Monad m, RenderMessage (HandlerSite m) msg) => (a -> m (Either msg b)) -> (b -> a) -> Field m a -> Field m b -- | Allows you to overwrite the error message on parse error. customErrorMessage :: forall (m :: Type -> Type) a. Monad m => SomeMessage (HandlerSite m) -> Field m a -> Field m a -- | Generate a FieldSettings from the given label. fieldSettingsLabel :: RenderMessage site msg => msg -> FieldSettings site -- | A helper function for creating custom fields. -- -- This is intended to help with the common case where a single input -- value is required, such as when parsing a text field. -- -- Since 1.1 parseHelper :: (Monad m, RenderMessage site FormMessage) => (Text -> Either FormMessage a) -> [Text] -> [FileInfo] -> m (Either (SomeMessage site) (Maybe a)) -- | A generalized version of parseHelper, allowing any type for the -- message indicating a bad parse. -- -- Since 1.3.6 parseHelperGen :: (Monad m, RenderMessage site msg) => (Text -> Either msg a) -> [Text] -> [FileInfo] -> m (Either (SomeMessage site) (Maybe a)) -- | Since a Field cannot be a Functor, it is not obvious how -- to "reuse" a Field on a newtype or otherwise equivalent type. -- This function allows you to convert a Field m a to a -- Field m b assuming you provide a bidirectional conversion -- between the two, through the first two functions. -- -- A simple example: -- --
--   import Data.Monoid
--   sumField :: (Functor m, Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m (Sum Int)
--   sumField = convertField Sum getSum intField
--   
-- -- Another example, not using a newtype, but instead creating a Lazy Text -- field: -- --
--   import qualified Data.Text.Lazy as TL
--   TextField :: (Functor m, Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TL.Text
--   lazyTextField = convertField TL.fromStrict TL.toStrict textField
--   
-- -- Since 1.3.16 convertField :: forall (m :: Type -> Type) a b. Functor m => (a -> b) -> (b -> a) -> Field m a -> Field m b -- | Removes a CSS class from the fsAttrs in a FieldSettings. -- --

Examples

-- --
--   >>> removeClass "form-control" [("class","form-control login-form"),("id","home-login")]
--   [("class","  login-form"),("id","home-login")]
--   
removeClass :: Text -> [(Text, Text)] -> [(Text, Text)] -- | Adds a CSS class to the fsAttrs in a FieldSettings. -- --

Examples

-- --
--   >>> addClass "login-form" [("class", "form-control"), ("id", "home-login")]
--   [("class","form-control login-form"),("id","home-login")]
--   
addClass :: Text -> [(Text, Text)] -> [(Text, Text)] defaultFormMessage :: FormMessage -> Text -- | Creates a input with type="number" and step=1. intField :: forall (m :: Type -> Type) i. (Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) => Field m i -- | Creates a input with type="number" and step=any. doubleField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Double -- | Creates an input with type="date", validating the input using -- the parseDate function. -- -- Add the time package and import the Data.Time.Calendar -- module to use this function. dayField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Day -- | An alias for timeFieldTypeTime. timeField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TimeOfDay -- | Creates an input with type="time". Browsers not supporting -- this type will fallback to a text field, and Yesod will parse the -- time as described in timeFieldTypeText. -- -- Add the time package and import the -- Data.Time.LocalTime module to use this function. timeFieldTypeTime :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TimeOfDay -- | Creates an input with type="text", parsing the time from an -- [H]H:MM[:SS] format, with an optional AM or PM (if not given, AM is -- assumed for compatibility with the 24 hour clock system). -- -- This function exists for backwards compatibility with the old -- implementation of timeField, which used to use -- type="text". Consider using timeField or -- timeFieldTypeTime for improved UX and validation from the -- browser. -- -- Add the time package and import the -- Data.Time.LocalTime module to use this function. timeFieldTypeText :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m TimeOfDay -- | Creates a <textarea> tag whose input is sanitized to -- prevent XSS attacks and is validated for having balanced tags. htmlField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Html -- | Creates a <textarea> tag whose returned value is -- wrapped in a Textarea; see Textarea for details. textareaField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Textarea -- | Creates an input with type="hidden"; you can use this to -- store information in a form that users shouldn't see (for example, -- Yesod stores CSRF tokens in a hidden field). hiddenField :: forall (m :: Type -> Type) p. (Monad m, PathPiece p, RenderMessage (HandlerSite m) FormMessage) => Field m p -- | Creates a input with type="text". textField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Text -- | Creates an input with type="password". passwordField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Text -- | Parses a Day from a Value. parseDate :: String -> Either FormMessage Day -- | Creates an input with type="email". Yesod will validate the -- email's correctness according to RFC5322 and canonicalize it by -- removing comments and whitespace (see Text.Email.Validate). emailField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Text -- | Creates an input with type="email" with the multiple -- attribute; browsers might implement this as taking a comma separated -- list of emails. Each email address is validated as described in -- emailField. multiEmailField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m [Text] -- | Creates an input with type="search". For browsers without -- autofocus support, a JS fallback is used if AutoFocus is -- true. searchField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => AutoFocus -> Field m Text -- | Creates an input with type="url", validating the URL -- according to RFC3986. urlField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Text -- | Creates a <select> tag for selecting one option. -- Example usage: -- --
--   areq (selectFieldList [("Value 1" :: Text, "value1"),("Value 2", "value2")]) "Which value?" Nothing
--   
selectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerFor site) a -- | Creates a <select> tag with <optgroup>s -- for selecting one option. selectFieldListGrouped :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, [(msg, a)])] -> Field (HandlerFor site) a -- | Creates a <select> tag with optional -- <optgroup>s for selecting one option. Example usage: -- --
--   areq (selectField $ optionsPairs [(MsgValue1, "value1"),(MsgValue2, "value2")]) "Which value?" Nothing
--   
selectField :: (Eq a, RenderMessage site FormMessage) => HandlerFor site (OptionList a) -> Field (HandlerFor site) a -- | Creates a <select> tag for selecting multiple options. multiSelectFieldList :: (Eq a, RenderMessage site msg) => [(msg, a)] -> Field (HandlerFor site) [a] -- | Creates a <select> tag for selecting multiple options. multiSelectField :: Eq a => HandlerFor site (OptionList a) -> Field (HandlerFor site) [a] -- | Creates an input with type="radio" for selecting one option. radioFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerFor site) a -- | Creates an input with type="checkbox" for selecting multiple -- options. checkboxesFieldList :: (Eq a, RenderMessage site msg) => [(msg, a)] -> Field (HandlerFor site) [a] -- | Creates an input with type="checkbox" for selecting multiple -- options. checkboxesField :: Eq a => HandlerFor site (OptionList a) -> Field (HandlerFor site) [a] -- | Creates an input with type="radio" for selecting one option. radioField :: (Eq a, RenderMessage site FormMessage) => HandlerFor site (OptionList a) -> Field (HandlerFor site) a -- | Allows the user to place the option radio widget somewhere in the -- template. For example: If you want a table of radio options to select. -- radioField is an example on how to use this function. withRadioField :: (Eq a, RenderMessage site FormMessage) => (Text -> WidgetFor site () -> WidgetFor site ()) -> (Text -> Text -> Bool -> Text -> WidgetFor site () -> WidgetFor site ()) -> HandlerFor site (OptionList a) -> Field (HandlerFor site) a -- | Creates a group of radio buttons to answer the question given in the -- message. Radio buttons are used to allow differentiating between an -- empty response (Nothing) and a no response (Just -- False). Consider using the simpler checkBoxField if you -- don't need to make this distinction. -- -- If this field is optional, the first radio button is labeled -- "<None>", the second "Yes" and the third "No". -- -- If this field is required, the first radio button is labeled "Yes" and -- the second "No". -- -- (Exact label titles will depend on localization). boolField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Bool -- | Creates an input with type="checkbox". While the default -- boolField implements a radio button so you can -- differentiate between an empty response (Nothing) and a no -- response (Just False), this simpler checkbox field returns an -- empty response as Just False. -- -- Note that this makes the field always optional. checkBoxField :: forall (m :: Type -> Type). Monad m => Field m Bool -- | Creates an OptionList, using a Map to implement the -- olReadExternal function. mkOptionList :: [Option a] -> OptionList a -- | Creates an OptionList, using a Map to implement the -- olReadExternalGrouped function. mkOptionListGrouped :: [(Text, [Option a])] -> OptionList a -- | Creates an OptionList from a list of (display-value, internal -- value) pairs. optionsPairs :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [(msg, a)] -> m (OptionList a) -- | Creates an OptionList from a list of (display-value, internal -- value) pairs. optionsPairsGrouped :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [(msg, [(msg, a)])] -> m (OptionList a) -- | Creates an OptionList from an Enum, using its -- Show instance for the user-facing value. optionsEnum :: (MonadHandler m, Show a, Enum a, Bounded a) => m (OptionList a) -- | Selects a list of Entitys with the given Filter and -- SelectOpts. The (a -> msg) function is then used to -- derive the display value for an OptionList. Example usage: -- --
--   Country
--      name Text
--      deriving Eq -- Must derive Eq
--   
-- --
--   data CountryForm = CountryForm
--     { country :: Entity Country
--     }
--   
--   countryNameForm :: AForm Handler CountryForm
--   countryNameForm = CountryForm
--           <$> areq (selectField countries) "Which country do you live in?" Nothing
--           where
--             countries = optionsPersist [] [Asc CountryName] countryName
--   
optionsPersist :: (YesodPersist site, PersistQueryRead backend, PathPiece (Key a), RenderMessage site msg, YesodPersistBackend site ~ backend, PersistRecordBackend a backend) => [Filter a] -> [SelectOpt a] -> (a -> msg) -> HandlerFor site (OptionList (Entity a)) -- | An alternative to optionsPersist which returns just the -- Key instead of the entire Entity. optionsPersistKey :: (YesodPersist site, PersistQueryRead backend, PathPiece (Key a), RenderMessage site msg, backend ~ YesodPersistBackend site, PersistRecordBackend a backend) => [Filter a] -> [SelectOpt a] -> (a -> msg) -> HandlerFor site (OptionList (Key a)) -- | A helper function for constucting selectFields with optional -- option groups. You may want to use this when you define your custom -- selectFields or radioFields. selectFieldHelper :: (Eq a, RenderMessage site FormMessage) => (Text -> Text -> [(Text, Text)] -> WidgetFor site () -> WidgetFor site ()) -> (Text -> Text -> Bool -> WidgetFor site ()) -> (Text -> Text -> [(Text, Text)] -> Text -> Bool -> Text -> WidgetFor site ()) -> Maybe (Text -> WidgetFor site ()) -> HandlerFor site (OptionList a) -> Field (HandlerFor site) a -- | Creates an input with type="file". fileField :: forall (m :: Type -> Type). Monad m => Field m FileInfo fileAFormReq :: forall (m :: Type -> Type). (MonadHandler m, RenderMessage (HandlerSite m) FormMessage) => FieldSettings (HandlerSite m) -> AForm m FileInfo fileAFormOpt :: forall (m :: Type -> Type). MonadHandler m => FieldSettings (HandlerSite m) -> AForm m (Maybe FileInfo) -- | Creates an input with type="color". The input value must be -- provided in hexadecimal format #rrggbb. colorField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m Text -- | Creates an input with type="datetime-local". The input value -- must be provided in YYYY-MM-DD(T| )HH:MM[:SS] format. datetimeLocalField :: forall (m :: Type -> Type). (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m LocalTime -- | Helper for creating runDB. -- -- Since 1.2.0 defaultRunDB :: PersistConfig c => (site -> c) -> (site -> PersistConfigPool c) -> PersistConfigBackend c (HandlerFor site) a -> HandlerFor site a -- | Helper for implementing getDBRunner. -- -- Since 1.2.0 defaultGetDBRunner :: (IsSqlBackend backend, YesodPersistBackend site ~ backend) => (site -> Pool backend) -> HandlerFor site (DBRunner site, HandlerFor site ()) -- | Like runDB, but transforms a Source. See -- respondSourceDB for an example, practical use case. -- -- Since 1.2.0 runDBSource :: YesodPersistRunner site => ConduitT () a (YesodDB site) () -> ConduitT () a (HandlerFor site) () -- | Extends respondSource to create a streaming database response -- body. respondSourceDB :: YesodPersistRunner site => ContentType -> ConduitT () (Flush Builder) (YesodDB site) () -> HandlerFor site TypedContent -- | Get the given entity by ID, or return a 404 not found if it doesn't -- exist. get404 :: forall (m :: Type -> Type) backend val. (MonadIO m, PersistStoreRead backend, PersistRecordBackend val backend) => Key val -> ReaderT backend m val -- | Get the given entity by unique key, or return a 404 not found if it -- doesn't exist. getBy404 :: forall backend val (m :: Type -> Type). (PersistUniqueRead backend, PersistRecordBackend val backend, MonadIO m) => Unique val -> ReaderT backend m (Entity val) -- | Create a new record in the database, returning an automatically -- created key, or raise a 400 bad request if a uniqueness constraint is -- violated. insert400 :: forall (m :: Type -> Type) backend val. (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend val backend, SafeToInsert val) => val -> ReaderT backend m (Key val) -- | Same as insert400, but doesn’t return a key. insert400_ :: forall (m :: Type -> Type) backend val. (MonadIO m, PersistUniqueWrite backend, PersistRecordBackend val backend, SafeToInsert val) => val -> ReaderT backend m () newsFeed :: MonadHandler m => Feed (Route (HandlerSite m)) -> m TypedContent -- | Same as newsFeed but for 'Feed Text'. Useful -- for cases where you are generating a feed of external links. newsFeedText :: MonadHandler m => Feed Text -> m TypedContent -- | Produce a default value of Static for a given file folder. -- -- Does not have index files or directory listings. The static files' -- contents must not change, however new files can be added. static :: FilePath -> IO Static -- | Same as static, but does not assumes that the files do not -- change and checks their modification time whenever a request is made. staticDevel :: FilePath -> IO Static -- | Template Haskell function that automatically creates routes for all of -- your static files. -- -- For example, if you used -- --
--   staticFiles "static/"
--   
-- -- and you had files "static/style.css" and -- "static/js/script.js", then the following top-level -- definitions would be created: -- --
--   style_css    = StaticRoute ["style.css"]    []
--   js_script_js = StaticRoute ["js", "script.js"] []
--   
-- -- Note that dots (.), dashes (-) and slashes -- (/) are replaced by underscores (_) to create valid -- Haskell identifiers. staticFiles :: FilePath -> Q [Dec] -- | Same as staticFiles, but takes an explicit list of files to -- create identifiers for. The files path given are relative to the -- static folder. For example, to create routes for the files -- "static/js/jquery.js" and -- "static/css/normalize.css", you would use: -- --
--   staticFilesList "static" ["js/jquery.js", "css/normalize.css"]
--   
-- -- This can be useful when you have a very large number of static files, -- but only need to refer to a few of them from Haskell. staticFilesList :: FilePath -> [FilePath] -> Q [Dec] -- | Same as staticFiles, but doesn't append an ETag to the query -- string. -- -- Using publicFiles will speed up the compilation, since there -- won't be any need for hashing files during compile-time. However, -- since the ETag ceases to be part of the URL, the Static subsite -- won't be able to set the expire date too far on the future. Browsers -- still will be able to cache the contents, however they'll need send a -- request to the server to see if their copy is up-to-date. publicFiles :: FilePath -> Q [Dec] -- | Similar to staticFilesList, but takes a mapping of unmunged -- names to fingerprinted file names. staticFilesMap :: FilePath -> Map FilePath FilePath -> Q [Dec] -- | Similar to staticFilesMergeMap, but also generates identifiers -- for all files in the specified directory that don't have a -- fingerprinted version. staticFilesMergeMap :: FilePath -> Map FilePath FilePath -> Q [Dec] base64md5 :: ByteString -> String -- | Combine multiple CSS files together. Common usage would be: -- --
--   >>> combineStylesheets' development def 'StaticR [style1_css, style2_css]
--   
-- -- Where development is a variable in your site indicated -- whether you are in development or production mode. -- -- Since 1.2.0 combineStylesheets' :: Bool -> CombineSettings -> Name -> [Route Static] -> Q Exp -- | Combine multiple JS files together. Common usage would be: -- --
--   >>> combineScripts' development def 'StaticR [script1_js, script2_js]
--   
-- -- Where development is a variable in your site indicated -- whether you are in development or production mode. -- -- Since 1.2.0 combineScripts' :: Bool -> CombineSettings -> Name -> [Route Static] -> Q Exp toSqlKey :: ToBackendKey SqlBackend record => Int64 -> Key record fromSqlKey :: ToBackendKey SqlBackend record => Key record -> Int64 -- | Lift a catchE operation to the new monad. liftCatch :: Catch e m (Maybe a) -> Catch e (MaybeT m) a -- | Convert a Maybe computation to MaybeT. hoistMaybe :: forall (m :: Type -> Type) b. Applicative m => Maybe b -> MaybeT m b renderJavascript :: Javascript -> Text asJavascriptUrl :: JavascriptUrl url -> JavascriptUrl url javascriptSettings :: Q ShakespeareSettings js :: QuasiQuoter jsFile :: FilePath -> Q Exp juliusFile :: FilePath -> Q Exp jsFileReload :: FilePath -> Q Exp juliusFileReload :: FilePath -> Q Exp juliusFileDebug :: FilePath -> Q Exp jsFileDebug :: FilePath -> Q Exp -- | Determine which identifiers are used by the given template, useful for -- creating systems like yesod devel. juliusUsedIdentifiers :: String -> [(Deref, VarType)] pprint :: (MonadIO m, Show a) => a -> m () -- | Lift a listen operation to the new monad. liftListen :: Monad m => Listen w m (Maybe a) -> Listen w (MaybeT m) a -- | Lift a pass operation to the new monad. liftPass :: Monad m => Pass w m (Maybe a) -> Pass w (MaybeT m) a -- | Transform the computation inside a MaybeT. -- -- mapMaybeT :: (m (Maybe a) -> n (Maybe b)) -> MaybeT m a -> MaybeT n b -- | Convert a MaybeT computation to ExceptT, with a default -- exception value. maybeToExceptT :: forall (m :: Type -> Type) e a. Functor m => e -> MaybeT m a -> ExceptT e m a -- | Convert a ExceptT computation to MaybeT, discarding the -- value of any exception. exceptToMaybeT :: forall (m :: Type -> Type) e a. Functor m => ExceptT e m a -> MaybeT m a -- | Override environment variable placeholders in the given Value -- with values from the environment. -- -- If the first argument is True, then all placeholders _must_ -- be provided by the actual environment. Otherwise, default values from -- the Value will be used. applyEnvValue :: Bool -> KeyMap Text -> Value -> Value -- | Get the actual environment as a HashMap from Text to -- Text. getCurrentEnv :: IO (KeyMap Text) -- | A convenience wrapper around applyEnvValue and -- getCurrentEnv applyCurrentEnv :: Bool -> Value -> IO Value -- | Do not use any environment variables, instead relying on defaults -- values in the config file. ignoreEnv :: EnvUsage -- | Use environment variables when available, otherwise use defaults. useEnv :: EnvUsage -- | Do not use default values from the config file, but instead take all -- overrides from the environment. If a value is missing, loading the -- file will throw an exception. requireEnv :: EnvUsage -- | Same as useEnv, but instead of the actual environment, use the -- provided HashMap as the environment. useCustomEnv :: KeyMap Text -> EnvUsage -- | Same as requireEnv, but instead of the actual environment, use -- the provided HashMap as the environment. requireCustomEnv :: KeyMap Text -> EnvUsage -- | Load the settings from the following three sources: -- -- -- -- For example, to load up settings from config/foo.yaml and -- allow overriding from the actual environment, you can use: -- --
--   loadYamlSettings ["config/foo.yaml"] [] useEnv
--   
loadYamlSettings :: FromJSON settings => [FilePath] -> [Value] -> EnvUsage -> IO settings -- | Same as loadYamlSettings, but get the list of runtime config -- files from the command line arguments. loadYamlSettingsArgs :: FromJSON settings => [Value] -> EnvUsage -> IO settings -- | Load the settings from the following three sources: -- -- loadAppSettings :: FromJSON settings => [FilePath] -> [Value] -> EnvUsage -> IO settings -- | Same as loadAppSettings, but get the list of runtime config -- files from the command line arguments. loadAppSettingsArgs :: FromJSON settings => [Value] -> EnvUsage -> IO settings -- | Location of the default config file. configSettingsYml :: FilePath -- | Helper for getApplicationDev in the scaffolding. Looks up PORT and -- DISPLAY_PORT and prints appropriate messages. getDevSettings :: Settings -> IO Settings -- | Helper for develMain in the scaffolding. develMainHelper :: IO (Settings, Application) -> IO () -- | Create a Logger value (from yesod-core) out of a -- LoggerSet (from fast-logger). makeYesodLogger :: LoggerSet -> IO Logger getAuth :: a -> Auth -- | Internal session key used to hold the authentication information. credsKey :: Text -- | Retrieves user credentials from the session, if user is authenticated. -- -- This function does not confirm that the credentials are valid, -- see maybeAuthIdRaw for more information. The first call in a -- request does a database request to make sure that the account is still -- in the database. defaultMaybeAuthId :: (MonadHandler m, HandlerSite m ~ master, YesodAuthPersist master, Typeable (AuthEntity master)) => m (Maybe (AuthId master)) -- | Default handler to show the login page. -- -- This is the default loginHandler. It concatenates plugin -- widgets and wraps the result in authLayout. See -- loginHandler for more details. defaultLoginHandler :: MonadAuthHandler master m => m Html loginErrorMessageI :: Route Auth -> AuthMessage -> AuthHandler master TypedContent -- | For HTML, set the message and redirect to the route. For JSON, send -- the message and a 401 status loginErrorMessage :: (MonadHandler m, YesodAuth (HandlerSite m)) => Route (HandlerSite m) -> Text -> m TypedContent messageJson401 :: MonadHandler m => Text -> m Html -> m TypedContent provideJsonMessage :: forall (m :: Type -> Type). Monad m => Text -> Writer (Endo [ProvidedRep m]) () setCredsRedirect :: (MonadHandler m, YesodAuth (HandlerSite m)) => Creds (HandlerSite m) -> m TypedContent -- | Sets user credentials for the session after checking them with -- authentication backends. setCreds :: (MonadHandler m, YesodAuth (HandlerSite m)) => Bool -> Creds (HandlerSite m) -> m () -- | Clears current user credentials for the session. clearCreds :: (MonadHandler m, YesodAuth (HandlerSite m)) => Bool -> m () -- | Similar to maybeAuthId, but additionally look up the value -- associated with the user's database identifier to get the value in the -- database. This assumes that you are using a Persistent database. maybeAuth :: (YesodAuthPersist master, val ~ AuthEntity master, Key val ~ AuthId master, PersistEntity val, Typeable val, MonadHandler m, HandlerSite m ~ master) => m (Maybe (Entity val)) -- | Similar to maybeAuth, but doesn’t assume that you are using a -- Persistent database. maybeAuthPair :: (YesodAuthPersist master, Typeable (AuthEntity master), MonadHandler m, HandlerSite m ~ master) => m (Maybe (AuthId master, AuthEntity master)) -- | Similar to maybeAuthId, but redirects to a login page if user -- is not authenticated or responds with error 401 if this is an API -- client (expecting JSON). requireAuthId :: (MonadHandler m, YesodAuth (HandlerSite m)) => m (AuthId (HandlerSite m)) -- | Similar to maybeAuth, but redirects to a login page if user is -- not authenticated or responds with error 401 if this is an API client -- (expecting JSON). requireAuth :: (YesodAuthPersist master, val ~ AuthEntity master, Key val ~ AuthId master, PersistEntity val, Typeable val, MonadHandler m, HandlerSite m ~ master) => m (Entity val) -- | Similar to requireAuth, but not tied to Persistent's -- Entity type. Instead, the AuthId and AuthEntity -- are returned in a tuple. requireAuthPair :: (YesodAuthPersist master, Typeable (AuthEntity master), MonadHandler m, HandlerSite m ~ master) => m (AuthId master, AuthEntity master) asHtml :: Html -> Html loggerSet :: Logger -> LoggerSet constrName :: (HasConstructor (Rep a), Generic a) => a -> String mkSlug :: Int -> IO Text cpprint :: (MonadIO m, Show a) => a -> m () -- | A version of AppSettings parsed at compile time from -- config/settings.yml. compileTimeAppSettings :: AppSettings mkBmSlug :: IO BmSlug mkNtSlug :: IO NtSlug policy :: HashingPolicy validatePasswordHash :: BCrypt -> Text -> Bool generateApiKey :: IO ApiKey hashApiKey :: ApiKey -> HashedApiKey cprint :: (MonadIO m, Show a) => a -> m () -- | Settings for widgetFile, such as which template languages to -- support and default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings -- | How static files should be combined. combineSettings :: CombineSettings widgetFile :: String -> Q Exp -- | Raw bytes at compile time of config/settings.yml configSettingsYmlBS :: ByteString -- | config/settings.yml, parsed to a Value. configSettingsYmlValue :: Value combineStylesheets :: Name -> [Route Static] -> Q Exp combineScripts :: Name -> [Route Static] -> Q Exp css_main_css :: StaticRoute css_popup_css :: StaticRoute css_tachyons_min_css :: StaticRoute css_tachyons_min_css_gz :: StaticRoute images_bluepin_gif :: StaticRoute js_app_min_js :: StaticRoute js_app_min_js_gz :: StaticRoute js_app_min_js_map :: StaticRoute js_app_min_js_map_gz :: StaticRoute js_html5shiv_min_js :: StaticRoute js_html5shiv_min_js_gz :: StaticRoute js_js_cookie_2_2_0_min_js :: StaticRoute js_js_cookie_2_2_0_min_js_gz :: StaticRoute migrateAll :: Migration migrateSchema :: Migration migrateIndexes :: Migration dumpMigration :: DB () runMigrations :: DB () toMigration :: [Text] -> Migration sqliteGroupConcat :: PersistField a => SqlExpr (Value a) -> SqlExpr (Value a) -> SqlExpr (Value Text) authenticatePassword :: Text -> Text -> DB (Maybe (Entity User)) getUserByName :: UserNameP -> DB (Maybe (Entity User)) getApiKeyUser :: ApiKey -> DB (Maybe (Entity User)) bookmarksTagsQuery :: Key User -> SharedP -> FilterP -> [Tag] -> Maybe Text -> Limit -> Page -> DB (Int, [(Entity Bookmark, Maybe Text)]) parseSearchQuery :: (Text -> SqlExpr (Value Bool)) -> Text -> Maybe (SqlQuery ()) parseTimeText :: (ParseTime t, MonadFail m, Alternative m) => Text -> m t allUserBookmarks :: Key User -> DB [(Entity Bookmark, Text)] withTags :: Key Bookmark -> DB [Entity BookmarkTag] getNote :: Key User -> NtSlug -> DB (Maybe (Entity Note)) getNoteList :: Key User -> Maybe Text -> SharedP -> Limit -> Page -> DB (Int, [Entity Note]) mkBookmarkTags :: Key User -> Key Bookmark -> [Tag] -> [BookmarkTag] fileBookmarkToBookmark :: UserId -> FileBookmark -> IO Bookmark bookmarkTofileBookmark :: Bookmark -> Text -> FileBookmark firefoxBookmarkNodeToBookmark :: UserId -> FFBookmarkNode -> IO [Bookmark] insertFileBookmarks :: Key User -> FilePath -> DB (Either String Int) readFileBookmarks :: MonadIO m => FilePath -> m (Either String [FileBookmark]) insertFFBookmarks :: Key User -> FilePath -> DB (Either String Int) readFFBookmarks :: MonadIO m => FilePath -> m (Either String FFBookmarkNode) exportFileBookmarks :: Key User -> FilePath -> DB () getFileBookmarks :: Key User -> DB [FileBookmark] isExpanded :: TagCloudMode -> Bool tagCountTop :: Key User -> Int -> DB [(Text, Int)] tagCountLowerBound :: Key User -> Int -> DB [(Text, Int)] tagCountRelated :: Key User -> [Tag] -> DB [(Text, Int)] fileNoteToNote :: UserId -> FileNote -> IO Note insertDirFileNotes :: Key User -> FilePath -> DB (Either String Int) gDefaultFormOptions :: Options toAccountSettingsForm :: User -> AccountSettingsForm updateUserFromAccountSettingsForm :: Key User -> AccountSettingsForm -> DB () toBookmarkFormList :: [(Entity Bookmark, Maybe Text)] -> [BookmarkForm] _toBookmarkForm' :: (Entity Bookmark, Maybe Text) -> BookmarkForm _toBookmarkForm :: (Entity Bookmark, [Entity BookmarkTag]) -> BookmarkForm _toBookmark :: UserId -> BookmarkForm -> IO Bookmark fetchBookmarkByUrl :: Key User -> Maybe Text -> DB (Maybe (Entity Bookmark, [Entity BookmarkTag])) maybeUpsertResult :: UpsertResult a -> Maybe a upsertBookmark :: Key User -> Maybe (Key Bookmark) -> Bookmark -> [Text] -> DB (UpsertResult (Key Bookmark)) updateBookmarkArchiveUrl :: Key User -> Key Bookmark -> Maybe Text -> DB () upsertNote :: Key User -> Maybe (Key Note) -> Note -> DB (UpsertResult (Key Note)) boolFromYesNo :: Text -> Bool boolToYesNo :: Bool -> Text readFileNoteTime :: MonadFail m => String -> m UTCTime showFileNoteTime :: UTCTime -> String entityDefListFormigrateSchema :: [EntityDef] module PathPiece encodeTag :: Text -> Text decodeTag :: Text -> Text instance Web.PathPieces.PathPiece ModelCustom.NtSlug instance Web.PathPieces.PathPiece ModelCustom.BmSlug instance Web.PathPieces.PathPiece Model.UserNameP instance Web.PathPieces.PathPiece Model.TagsP instance Web.PathPieces.PathPiece Model.SharedP instance Web.PathPieces.PathPiece Model.FilterP module Foundation data App App :: AppSettings -> Static -> ConnectionPool -> Manager -> Logger -> App [appSettings] :: App -> AppSettings -- | Settings for static file serving. [appStatic] :: App -> Static -- | Database connection pool. [appConnPool] :: App -> ConnectionPool [appHttpManager] :: App -> Manager [appLogger] :: App -> Logger type Handler = HandlerFor App type Widget = WidgetFor App () resourcesApp :: [ResourceTree String] session_timeout_minutes :: Int isAuthenticated :: Handler AuthResult addAppScripts :: (MonadWidget m, HandlerSite m ~ App) => m () popupLayout :: Widget -> Handler Html maybeAuthUsername :: Handler (Maybe Text) ultDestKey :: Text userNameKey :: Text dbAuthPluginName :: Text dbAuthPlugin :: AuthPlugin App dbLoginR :: AuthRoute dbPostLoginR :: AuthHandler master TypedContent dbLoginCreds :: Text -> Text -> Creds master authenticateCreds :: (MonadHandler m, HandlerSite m ~ App) => Creds App -> m (AuthenticationResult App) unsafeHandler :: App -> Handler a -> IO a instance GHC.Read.Read (Yesod.Routes.Class.Route Foundation.App) instance GHC.Show.Show (Yesod.Routes.Class.Route Foundation.App) instance GHC.Classes.Eq (Yesod.Routes.Class.Route Foundation.App) instance GHC.Generics.Generic (Yesod.Routes.Class.Route Foundation.App) instance Yesod.Routes.Class.ParseRoute Foundation.App instance Yesod.Routes.Class.RenderRoute Foundation.App instance Yesod.Routes.Class.RouteAttrs Foundation.App instance Yesod.Persist.Core.YesodPersist Foundation.App instance Yesod.Persist.Core.YesodPersistRunner Foundation.App instance Yesod.Core.Class.Yesod.Yesod Foundation.App instance Yesod.Auth.YesodAuth Foundation.App instance Yesod.Auth.YesodAuthPersist Foundation.App instance Text.Shakespeare.I18N.RenderMessage Foundation.App Yesod.Form.Types.FormMessage instance Network.HTTP.Client.Types.HasHttpManager Foundation.App module Import module Handler.Home getHomeR :: Handler Html module Handler.Edit deleteDeleteR :: Int64 -> Handler Html postReadR :: Int64 -> Handler Html postStarR :: Int64 -> Handler Html postUnstarR :: Int64 -> Handler Html _setSelected :: Int64 -> Bool -> Handler Html requireResource :: UserId -> Key Bookmark -> DBM Handler Bookmark module Handler.Docs getDocsSearchR :: Handler Html -- | Common handler functions. module Handler.Common getFaviconR :: Handler TypedContent getRobotsR :: Handler TypedContent lookupPagingParams :: Handler (Maybe Int64, Maybe Int64) getUrlParam :: Read a => Text -> Handler (Maybe a) getUrlSessionParam :: forall a. (Show a, Read a) => Text -> Handler (Maybe a) lookupTagCloudMode :: MonadHandler m => m (Maybe TagCloudMode) setTagCloudMode :: MonadHandler m => TagCloudMode -> m () getTagCloudMode :: MonadHandler m => Bool -> [Tag] -> m TagCloudMode module Handler.User getUserR :: UserNameP -> Handler Html getUserSharedR :: UserNameP -> SharedP -> Handler Html getUserFilterR :: UserNameP -> FilterP -> Handler Html getUserTagsR :: UserNameP -> TagsP -> Handler Html _getUser :: UserNameP -> SharedP -> FilterP -> TagsP -> Handler Html postUserTagCloudR :: Handler () postUserTagCloudModeR :: Handler () _updateTagCloudMode :: TagCloudMode -> Handler () bookmarkToRssEntry :: (Entity Bookmark, Maybe Text) -> FeedEntry Text getUserFeedR :: UserNameP -> Handler RepRss getUserFeedSharedR :: UserNameP -> SharedP -> Handler RepRss getUserFeedFilterR :: UserNameP -> FilterP -> Handler RepRss getUserFeedTagsR :: UserNameP -> TagsP -> Handler RepRss _getUserFeed :: UserNameP -> SharedP -> FilterP -> TagsP -> Handler RepRss module Handler.Notes getNotesR :: UserNameP -> Handler Html getNoteR :: UserNameP -> NtSlug -> Handler Html getAddNoteSlimViewR :: Handler Html getAddNoteViewR :: UserNameP -> Handler Html deleteDeleteNoteR :: Int64 -> Handler Html postAddNoteR :: Handler Text requireResource :: UserId -> Key Note -> DBM Handler Note _handleFormSuccess :: NoteForm -> Handler (UpsertResult (Key Note)) data NoteForm NoteForm :: Maybe Int64 -> Maybe NtSlug -> Maybe Text -> Maybe Textarea -> Maybe Bool -> Maybe Bool -> Maybe UTCTimeStr -> Maybe UTCTimeStr -> NoteForm [_id] :: NoteForm -> Maybe Int64 [_slug] :: NoteForm -> Maybe NtSlug [_title] :: NoteForm -> Maybe Text [_text] :: NoteForm -> Maybe Textarea [_isMarkdown] :: NoteForm -> Maybe Bool [_shared] :: NoteForm -> Maybe Bool [_created] :: NoteForm -> Maybe UTCTimeStr [_updated] :: NoteForm -> Maybe UTCTimeStr gNoteFormOptions :: Options noteFormUrl :: Handler NoteForm _toNote :: UserId -> NoteForm -> IO Note noteToRssEntry :: (Route App -> Text) -> UserNameP -> Entity Note -> FeedEntry Text getNotesFeedR :: UserNameP -> Handler RepRss instance GHC.Generics.Generic Handler.Notes.NoteForm instance GHC.Read.Read Handler.Notes.NoteForm instance GHC.Classes.Eq Handler.Notes.NoteForm instance GHC.Show.Show Handler.Notes.NoteForm instance Data.Aeson.Types.FromJSON.FromJSON Handler.Notes.NoteForm instance Data.Aeson.Types.ToJSON.ToJSON Handler.Notes.NoteForm module Handler.Archive shouldArchiveBookmark :: User -> Key Bookmark -> Handler Bool getArchiveManager :: Handler Manager archiveBookmarkUrl :: Key Bookmark -> String -> Handler () _isArchiveBlacklisted :: Bookmark -> Bool _parseRefreshHeaderUrl :: ByteString -> Maybe Text _fetchArchiveSubmitInfo :: Handler (Either String (String, String)) _parseSubstring :: Parser ByteString -> Parser Char -> ByteString -> Either String String fetchPageTitle :: String -> Handler (Either String Text) _buildArchiveSubmitRequest :: (String, String) -> String -> Handler Request buildRequest :: String -> Handler Request _archiveUserAgent :: Handler ByteString module Handler.Add getAddViewR :: Handler Html bookmarkFormUrl :: Handler BookmarkForm postAddR :: Handler Text _handleFormSuccess :: BookmarkForm -> Handler (UpsertResult (Key Bookmark)) postLookupTitleR :: Handler () module Handler.AccountSettings getAccountSettingsR :: Handler Html postEditAccountSettingsR :: Handler () getChangePasswordR :: Handler Html postChangePasswordR :: Handler Html validateNewPassword :: Text -> Handler (Maybe Text) module Application -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) -- | The main function for an executable running this site. appMain :: IO () -- | main function for use by yesod devel develMain :: IO () makeFoundation :: AppSettings -> IO App makeLogWare :: App -> IO Middleware getApplicationRepl :: IO (Int, App, Application) shutdownApp :: App -> IO () -- | Run a handler handler :: Handler a -> IO a -- | Run DB queries db :: ReaderT SqlBackend (HandlerFor App) a -> IO a instance Yesod.Core.Class.Dispatch.YesodDispatch Foundation.App