>>> some (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> some Nothingnothing
Example1 expression
>>> take 5 <$> some (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case some parser will attempt to
parse parser one or more times until it fails.
>>> many (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
>>> many NothingJust []
Example1 expression
>>> take 5 <$> many (Just 1)* hangs forever *
Note that this function can be used with Parsers based on
Applicatives. In that case many parser will attempt to
parse parser zero or more times until it fails.
sequence computations and combine their results (<*> and liftA2).
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:
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.
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.
Example1 expression
>>> Just 2 *> Just 3Just 3
Example1 expression
>>> Nothing *> Just 3Nothing
Of course a more interesting use case would be to have effectful
computations instead of just returning pure values.
Example4 expressions
>>> import Data.Char>>> import GHC.Internal.Text.ParserCombinators.ReadP>>> let p = string "my name is " *> munch1 isAlpha <* eof>>> readP_to_S p "my name is Simon"[("Simon","")]
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.
A common use of join is to run an IO computation returned from
an GHC.Conc.STM transaction, since GHC.Conc.STM transactions
can't perform IO directly. Recall that
GHC.Internal.Conc.atomically :: STM a -> IO a
is used to run GHC.Conc.STM transactions atomically. So, by
specializing the types of GHC.Internal.Conc.atomically and join to
GHC.Internal.Conc.atomically :: STM (IO b) -> IO (IO b)
join :: IO (IO b) -> IO b
we can compose them as
join . GHC.Internal.Conc.atomically :: STM (IO b) -> IO b
to run an GHC.Conc.STM transaction and the IO action it
returns.
A common use of forever is to process input from network sockets,
System.IO.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:
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.
Common uses of guard include conditionally signalling an error in
an error monad and conditionally rejecting the current choice in an
Alternative-based parser.
As an example of signalling 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:
Example1 expression
>>> safeDiv 4 0Nothing
Example1 expression
>>> safeDiv 4 2Just 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 Monaddo-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
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:
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:
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. Data.Semigroup.Sum and Data.Semigroup.Product.
NOTE: Semigroup is a superclass of Monoid since base-4.11.0.0.
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.
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.
Monoidp => Monoid (Par1p)Defined in ghc-internal-9.1401.0 · GHC.Internal.Generics
Semigroupa => Monoid (Maybea)Defined in ghc-internal-9.1401.0 · GHC.Internal.Base
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
Semigroupa => Monoid (Chunka)Defined in optparse-applicative-0.19.0.0 · Options.Applicative.Help.Chunk
Bitsa => Monoid (Iora)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Bits
Bitsa => Monoid (Xora)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Bits
FiniteBitsa => Monoid (Anda)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Bits
This constraint is arguably too strong. However,
as some types (such as Natural) have undefined complement, this is the
only safe choice.
FiniteBitsa => Monoid (Iffa)Defined in ghc-internal-9.1401.0 · GHC.Internal.Data.Bits
This constraint is arguably
too strong. However, as some types (such as Natural) have undefined
complement, this is the only safe choice.
Orda => Monoid (Seta)Defined in containers-0.8 · Data.Set.Internal
This is a potentially unsafe function since it allows a resource to escape
its scope. For example, you might use Managed to safely acquire a
file handle, like this:
import qualified System.IO as IO
example :: Managed Handle
example = managed (IO.withFile "foo.txt" IO.ReadMode)
... and if you never used the with function then you would never run the
risk of accessing the Handle after the file was closed. However, if you
use with then you can incorrectly access the handle after the handle is
closed, like this:
bad :: IO ()
bad = do
handle <- with example return
IO.hPutStrLn handle "bar" -- This will fail because the handle is closed
... so only use with if you know what you are doing and you're returning
a value that is not a resource being managed.
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
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.
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.
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.
Note that even though the type says Either this utility actually always
succeeds and returns a Right value. The only reason for the Either is
compatibility with the old type from the system-filepath package.
DataTextDefined in text-2.1.3 · Data.Text · orphan
This instance preserves data abstraction at the cost of inefficiency.
We omit reflection services for the sake of data abstraction.
This instance was created by copying the updated behavior of
Data.Set.Set and Data.Map.Data.Map.Map. If you
feel a mistake has been made, please feel free to submit
improvements.
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.
Instances12Eq, Data, Ord, Read, Show, Generic, …
EqUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
DataUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
OrdUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
ReadUTCTimeDefined in time-1.15 · Data.Time.Format.Parse · orphan
ShowUTCTimeDefined in time-1.15 · Data.Time.LocalTime.Internal.ZonedTime · orphan
GenericUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
NFDataUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
FormatTimeUTCTimeDefined in time-1.15 · Data.Time.Format.Format.Instances · orphan
ParseTimeUTCTimeDefined in time-1.15 · Data.Time.Format.Parse.Instances · orphan
ISO8601UTCTimeDefined in time-1.15 · Data.Time.Format.ISO8601
yyyy-mm-ddThh:mm:ss[.ss]Z [ISO 8601:2004(E) sec. 4.3.2 extended format]
LiftUTCTimeDefined in time-1.15 · Data.Time.Clock.Internal.UTCTime
This is a length of time, as measured by UTC.
It has a precision of one picosecond (10^-12 s).
Conversion functions such as fromInteger and realToFrac will treat it as seconds.
For example, (0.010 :: NominalDiffTime) corresponds to 10 milliseconds.
Enumeration functions will treat it as picoseconds.
It ignores leap-seconds, so it's not necessarily a fixed amount of clock time.
For instance, 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC (+ 1 day),
regardless of whether a leap-second intervened.
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:
whether it manages input or output or both;
whether it is open, closed or semi-closed;
whether the object is seekable;
whether buffering is disabled, or enabled on a line or block basis;
a buffer (whose length may be zero).
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.
Instances4Eq, Show, InputSource, OutputSink
EqHandleDefined in ghc-internal-9.1401.0 · GHC.Internal.IO.Handle.Types
ShowHandleDefined in ghc-internal-9.1401.0 · GHC.Internal.IO.Handle.Types
InputSourceHandleDefined in streaming-commons-0.2.3.1 · Data.Streaming.Process.Internal
OutputSinkHandleDefined in streaming-commons-0.2.3.1 · Data.Streaming.Process.Internal
indicates program failure with an exit code.
The exact interpretation of the code is
operating-system dependent. In particular, some values
may be prohibited (e.g. 0 on a POSIX-compliant system).
& is a reverse application operator. This provides notational
convenience. Its precedence is one higher than that of the forward
application operator $, which allows & to be nested in $.
This is a version of flipid, where id is specialized from a -> a to (a -> b) -> (a -> b)
which by the associativity of (->) is (a -> b) -> a -> b.
flipping this yields a -> (a -> b) -> b which is the type signature of &
Examples
Example1 expression
>>> 5 & (+1) & show"6"
Example1 expression
>>> sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946