Copyright | (c) Lars Brünjes, 2016 |
---|---|
License | MIT |
Maintainer | brunjlar@gmail.com |
Stability | experimental |
Portability | portable |
Safe Haskell | None |
Language | Haskell2010 |
This module simply reexports a selection of commonly used standard types and functions.
- class NFData a where
- rnf :: a -> ()
- deepseq :: NFData a => a -> b -> b
- force :: NFData a => a -> a
- (&) :: a -> (a -> b) -> b
- (^.) :: s -> Getting a s a -> a
- (.~) :: ASetter s t a b -> b -> s -> t
- type Lens' s a = Lens s s a a
- type Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s
- to :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' * * p f s a
- lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b
- when :: Applicative f => Bool -> f () -> f ()
- unless :: Applicative f => Bool -> f () -> f ()
- forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- void :: Functor f => f a -> f ()
- replicateM :: Applicative m => Int -> m a -> m [a]
- forever :: Applicative f => f a -> f b
- guard :: Alternative f => Bool -> f ()
- newtype Identity a :: * -> * = Identity {
- runIdentity :: a
- class Monad m => MonadIO m where
- class Monad m => MonadRandom m where
- getRandom :: Random a => m a
- getRandomR :: Random a => (a, a) -> m a
- getRandom :: MonadRandom m => forall a. Random a => m a
- getRandomR :: MonadRandom m => forall a. Random a => (a, a) -> m a
- type Rand g = RandT g Identity
- data RandT g m a :: * -> (* -> *) -> * -> *
- runRand :: Rand g a -> g -> (a, g)
- evalRand :: Rand g a -> g -> a
- runRandT :: RandT g m a -> g -> m (a, g)
- evalRandT :: Monad m => RandT g m a -> g -> m a
- data StdGen :: *
- mkStdGen :: Int -> StdGen
- class Monad m => MonadState s m | m -> s where
- lift :: MonadTrans t => forall m a. Monad m => m a -> t m a
- type State s = StateT s Identity
- data StateT s m a :: * -> (* -> *) -> * -> *
- modify :: Monad m => (s -> s) -> StateT s m ()
- runState :: State s a -> s -> (a, s)
- evalState :: State s a -> s -> a
- execState :: State s a -> s -> s
- runStateT :: StateT s m a -> s -> m (a, s)
- evalStateT :: Monad m => StateT s m a -> s -> m a
- execStateT :: Monad m => StateT s m a -> s -> m s
- type Writer w = WriterT w Identity
- data WriterT w m a :: * -> (* -> *) -> * -> *
- tell :: Monad m => w -> WriterT w m ()
- runWriter :: Writer w a -> (a, w)
- execWriter :: Writer w a -> w
- runWriterT :: WriterT w m a -> m (a, w)
- execWriterT :: Monad m => WriterT w m a -> m w
- lefts :: [Either a b] -> [a]
- rights :: [Either a b] -> [b]
- toList :: Foldable t => forall a. t a -> [a]
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- sort :: Ord a => [a] -> [a]
- sortBy :: (a -> a -> Ordering) -> [a] -> [a]
- minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- foldl' :: Foldable t => forall b a. (b -> a -> b) -> b -> t a -> b
- intercalate :: [a] -> [[a]] -> [a]
- catMaybes :: [Maybe a] -> [a]
- fromJust :: Maybe a -> a
- fromMaybe :: a -> Maybe a -> a
- (<>) :: Monoid m => m -> m -> m
- getDirectoryContents :: FilePath -> IO [FilePath]
- getArgs :: IO [String]
- (</>) :: FilePath -> FilePath -> FilePath
- (<.>) :: FilePath -> String -> FilePath
- withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
- data IOMode :: *
- hPutStr :: Handle -> String -> IO ()
- hPutStrLn :: Handle -> String -> IO ()
- printf :: PrintfType r => String -> r
Documentation
A class of types that can be fully evaluated.
Since: 1.1.0.0
Nothing
NFData Bool | |
NFData Char | |
NFData Double | |
NFData Float | |
NFData Int | |
NFData Int8 | |
NFData Int16 | |
NFData Int32 | |
NFData Int64 | |
NFData Integer | |
NFData Word | |
NFData Word8 | |
NFData Word16 | |
NFData Word32 | |
NFData Word64 | |
NFData CallStack | Since: 1.4.2.0 |
NFData TypeRep | NOTE: Only defined for Since: 1.4.0.0 |
NFData () | |
NFData TyCon | NOTE: Only defined for Since: 1.4.0.0 |
NFData ThreadId | Since: 1.4.0.0 |
NFData Natural | Since: 1.4.0.0 |
NFData Void | Since: 1.4.0.0 |
NFData Version | Since: 1.3.0.0 |
NFData Unique | Since: 1.4.0.0 |
NFData ExitCode | Since: 1.4.2.0 |
NFData CChar | Since: 1.4.0.0 |
NFData CSChar | Since: 1.4.0.0 |
NFData CUChar | Since: 1.4.0.0 |
NFData CShort | Since: 1.4.0.0 |
NFData CUShort | Since: 1.4.0.0 |
NFData CInt | Since: 1.4.0.0 |
NFData CUInt | Since: 1.4.0.0 |
NFData CLong | Since: 1.4.0.0 |
NFData CULong | Since: 1.4.0.0 |
NFData CLLong | Since: 1.4.0.0 |
NFData CULLong | Since: 1.4.0.0 |
NFData CFloat | Since: 1.4.0.0 |
NFData CDouble | Since: 1.4.0.0 |
NFData CPtrdiff | Since: 1.4.0.0 |
NFData CSize | Since: 1.4.0.0 |
NFData CWchar | Since: 1.4.0.0 |
NFData CSigAtomic | Since: 1.4.0.0 |
NFData CClock | Since: 1.4.0.0 |
NFData CTime | Since: 1.4.0.0 |
NFData CUSeconds | Since: 1.4.0.0 |
NFData CSUSeconds | Since: 1.4.0.0 |
NFData CFile | Since: 1.4.0.0 |
NFData CFpos | Since: 1.4.0.0 |
NFData CJmpBuf | Since: 1.4.0.0 |
NFData CIntPtr | Since: 1.4.0.0 |
NFData CUIntPtr | Since: 1.4.0.0 |
NFData CIntMax | Since: 1.4.0.0 |
NFData CUIntMax | Since: 1.4.0.0 |
NFData All | Since: 1.4.0.0 |
NFData Any | Since: 1.4.0.0 |
NFData Fingerprint | Since: 1.4.0.0 |
NFData SrcLoc | Since: 1.4.2.0 |
NFData ByteString | |
NFData ByteString | |
NFData IntSet | |
NFData Doc | |
NFData TextDetails | |
NFData LocalTime | |
NFData ZonedTime | |
NFData TimeOfDay | |
NFData TimeZone | |
NFData UTCTime | |
NFData NominalDiffTime | |
NFData Day | |
NFData UniversalTime | |
NFData DiffTime | |
NFData a => NFData [a] | |
NFData a => NFData (Maybe a) | |
NFData a => NFData (Ratio a) | |
NFData (Ptr a) | Since: 1.4.2.0 |
NFData (FunPtr a) | Since: 1.4.2.0 |
NFData a => NFData (IntMap a) | |
NFData a => NFData (Identity a) | Since: 1.4.0.0 |
NFData a => NFData (Min a) | Since: 1.4.2.0 |
NFData a => NFData (Max a) | Since: 1.4.2.0 |
NFData a => NFData (First a) | Since: 1.4.2.0 |
NFData a => NFData (Last a) | Since: 1.4.2.0 |
NFData m => NFData (WrappedMonoid m) | Since: 1.4.2.0 |
NFData a => NFData (Option a) | Since: 1.4.2.0 |
NFData a => NFData (NonEmpty a) | Since: 1.4.2.0 |
NFData (Fixed a) | Since: 1.3.0.0 |
NFData a => NFData (Complex a) | |
NFData (StableName a) | Since: 1.4.0.0 |
NFData a => NFData (ZipList a) | Since: 1.4.0.0 |
NFData a => NFData (Dual a) | Since: 1.4.0.0 |
NFData a => NFData (Sum a) | Since: 1.4.0.0 |
NFData a => NFData (Product a) | Since: 1.4.0.0 |
NFData a => NFData (First a) | Since: 1.4.0.0 |
NFData a => NFData (Last a) | Since: 1.4.0.0 |
NFData (IORef a) | NOTE: Only strict in the reference and not the referenced value. Since: 1.4.2.0 |
NFData a => NFData (Down a) | Since: 1.4.0.0 |
NFData (MVar a) | NOTE: Only strict in the reference and not the referenced value. Since: 1.4.2.0 |
NFData a => NFData (Digit a) | |
NFData a => NFData (Node a) | |
NFData a => NFData (Elem a) | |
NFData a => NFData (FingerTree a) | |
NFData a => NFData (Tree a) | |
NFData a => NFData (Seq a) | |
NFData a => NFData (Set a) | |
NFData a => NFData (Vector a) | |
NFData (Vector a) | |
NFData (Vector a) | |
NFData (Vector a) | |
NFData a => NFData (HashSet a) | |
NFData (IVar a) | |
NFData a => NFData (Doc a) | |
NFData a => NFData (AnnotDetails a) | |
NFData a => NFData (Probability a) # | |
NFData (a -> b) | This instance is for convenience and consistency with Since: 1.3.0.0 |
(NFData a, NFData b) => NFData (Either a b) | |
(NFData a, NFData b) => NFData (a, b) | |
(NFData a, NFData b) => NFData (Array a b) | |
(NFData a, NFData b) => NFData (Arg a b) | Since: 1.4.2.0 |
NFData (Proxy k a) | Since: 1.4.0.0 |
NFData (STRef s a) | NOTE: Only strict in the reference and not the referenced value. Since: 1.4.2.0 |
(NFData k, NFData a) => NFData (Map k a) | |
(NFData k, NFData v) => NFData (HashMap k v) | |
(NFData k, NFData v) => NFData (Leaf k v) | |
NFData (MVector s a) | |
NFData (MVector s a) | |
NFData (MVector s a) | |
NFData a => NFData (Vector n a) # | |
NFData (Component f g) # | |
(NFData a, NFData b, NFData c) => NFData (a, b, c) | |
NFData a => NFData (Const k a b) | Since: 1.4.0.0 |
NFData b => NFData (Tagged k s b) | |
NFData a => NFData (Matrix m n a) # | |
(NFData (s a), NFData (t a)) => NFData (Pair s t a) # | |
(NFData a, NFData b, NFData c, NFData d) => NFData (a, b, c, d) | |
(NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData (a1, a2, a3, a4, a5) | |
NFData (Model f g a b c) # | |
(NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData (a1, a2, a3, a4, a5, a6) | |
(NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData (a1, a2, a3, a4, a5, a6, a7) | |
(NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8) => NFData (a1, a2, a3, a4, a5, a6, a7, a8) | |
(NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8, NFData a9) => NFData (a1, a2, a3, a4, a5, a6, a7, a8, a9) | |
deepseq :: NFData a => a -> b -> b #
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.
Since: 1.1.0.0
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 ()
Since: 1.2.0.0
(^.) :: s -> Getting a s a -> a infixl 8 #
View the value pointed to by a Getter
or Lens
or the
result of folding over all the results of a Fold
or
Traversal
that points at a monoidal values.
This is the same operation as view
with the arguments flipped.
The fixity and semantics are such that subsequent field accesses can be
performed with (.
).
>>>
(a,b)^._2
b
>>>
("hello","world")^._2
"world"
>>>
import Data.Complex
>>>
((0, 1 :+ 2), 3)^._1._2.to magnitude
2.23606797749979
(^.
) :: s ->Getter
s a -> a (^.
) ::Monoid
m => s ->Fold
s m -> m (^.
) :: s ->Iso'
s a -> a (^.
) :: s ->Lens'
s a -> a (^.
) ::Monoid
m => s ->Traversal'
s m -> m
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 #
Replace the target of a Lens
or all of the targets of a Setter
or Traversal
with a constant value.
This is an infix version of set
, provided for consistency with (.=
).
f<$
a ≡mapped
.~
f$
a
>>>
(a,b,c,d) & _4 .~ e
(a,b,c,e)
>>>
(42,"world") & _1 .~ "hello"
("hello","world")
>>>
(a,b) & both .~ c
(c,c)
(.~
) ::Setter
s t a b -> b -> s -> t (.~
) ::Iso
s t a b -> b -> s -> t (.~
) ::Lens
s t a b -> b -> s -> t (.~
) ::Traversal
s t a b -> b -> s -> t
type Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s #
A Getter
describes how to retrieve a single value in a way that can be
composed with other LensLike
constructions.
Unlike a Lens
a Getter
is read-only. Since a Getter
cannot be used to write back there are no Lens
laws that can be applied to
it. In fact, it is isomorphic to an arbitrary function from (s -> a)
.
Moreover, a Getter
can be used directly as a Fold
,
since it just ignores the Applicative
.
to :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' * * p f s a #
when :: Applicative f => Bool -> f () -> f () #
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.
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when
.
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) #
void :: Functor f => f a -> f () #
discards or ignores the result of evaluation, such
as the return value of an void
valueIO
action.
Examples
Replace the contents of a
with unit:Maybe
Int
>>>
void Nothing
Nothing>>>
void (Just 3)
Just ()
Replace the contents of an
with unit,
resulting in an Either
Int
Int
: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
replicateM :: Applicative m => Int -> m a -> m [a] #
performs the action replicateM
n actn
times,
gathering the results.
forever :: Applicative f => f a -> f b #
repeats the action infinitely.forever
act
newtype Identity a :: * -> * #
Identity functor and monad. (a non-strict monad)
Since: 4.8.0.0
Identity | |
|
class Monad m => MonadIO m where #
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:
MonadIO IO | |
MonadIO m => MonadIO (CatchT m) | |
MonadIO m => MonadIO (MaybeT m) | |
MonadIO m => MonadIO (Codensity m) | |
MonadIO m => MonadIO (ListT m) | |
MonadIO m => MonadIO (ListT m) | |
MonadIO m => MonadIO (SafeT m) | |
MonadIO m => MonadIO (RandT g m) | |
MonadIO m => MonadIO (IdentityT * m) | |
(Functor f, MonadIO m) => MonadIO (FreeT f m) | |
(Error e, MonadIO m) => MonadIO (ErrorT e m) | |
MonadIO m => MonadIO (ExceptT e m) | |
MonadIO m => MonadIO (StateT s m) | |
MonadIO m => MonadIO (StateT s m) | |
(Monoid w, MonadIO m) => MonadIO (WriterT w m) | |
(Monoid w, MonadIO m) => MonadIO (WriterT w m) | |
MonadIO m => MonadIO (ContT * r m) | |
MonadIO m => MonadIO (ReaderT * r m) | |
(Monoid w, MonadIO m) => MonadIO (RWST r w s m) | |
(Monoid w, MonadIO m) => MonadIO (RWST r w s m) | |
MonadIO m => MonadIO (Proxy a' a b' b m) | |
class Monad m => MonadRandom m where #
An interface to random number generation monads.
(Monad m, RandomGen g) => MonadRandom (RandT g m) | |
getRandom :: MonadRandom m => forall a. Random a => m a #
Return a randomly-selected value of type a
. See
random
for details.
getRandomR :: MonadRandom m => forall a. Random a => (a, a) -> m a #
Return a randomly-selected value of type a
in the range
[lo,hi]. See randomR
for details.
data RandT g m a :: * -> (* -> *) -> * -> * #
A monad transformer which adds a random number generator to an existing monad.
(Monad m, RandomGen g) => MonadSplit g (RandT g m) | |
MonadState s m => MonadState s (RandT g m) | |
MonadReader r m => MonadReader r (RandT g m) | |
MonadWriter w m => MonadWriter w (RandT g m) | |
MonadTrans (RandT g) | |
Monad m => Monad (RandT g m) | |
Functor m => Functor (RandT g m) | |
MonadFix m => MonadFix (RandT g m) | |
(Functor m, Monad m) => Applicative (RandT g m) | |
(Monad m, RandomGen g) => MonadRandom (RandT g m) | |
MonadIO m => MonadIO (RandT g m) | |
(Functor m, MonadPlus m) => Alternative (RandT g m) | |
MonadPlus m => MonadPlus (RandT g m) | |
runRand :: Rand g a -> g -> (a, g) #
Run a random computation using the generator g
, returning the result
and the updated generator.
evalRand :: Rand g a -> g -> a #
Evaluate a random computation using the generator g
. Note that the
generator g
is not returned, so there's no way to recover the
updated version of g
.
runRandT :: RandT g m a -> g -> m (a, g) #
Run a RandT computation using the generator g
, returning the result and
the updated generator.
evalRandT :: Monad m => RandT g m a -> g -> m a #
Evaluate a RandT computation using the generator g
. Note that the
generator g
is not returned, so there's no way to recover the
updated version of g
.
The StdGen
instance of RandomGen
has a genRange
of at least 30 bits.
The result of repeatedly using next
should be at least as statistically
robust as the Minimal Standard Random Number Generator described by
[System.Random, System.Random].
Until more is known about implementations of split
, all we require is
that split
deliver generators that are (a) not identical and
(b) independently robust in the sense just given.
The Show
and Read
instances of StdGen
provide a primitive way to save the
state of a random number generator.
It is required that
.read
(show
g) == g
In addition, reads
may be used to map an arbitrary string (not necessarily one
produced by show
) onto a value of type StdGen
. In general, the Read
instance of StdGen
has the following properties:
- It guarantees to succeed on any string.
- It guarantees to consume only a finite portion of the string.
- Different argument strings are likely to result in different results.
class Monad m => MonadState s m | m -> s where #
Minimal definition is either both of get
and put
or just state
MonadState s m => MonadState s (CatchT m) | |
MonadState s m => MonadState s (SafeT m) | |
MonadState s m => MonadState s (ListT m) | |
MonadReader r m => MonadState r (Codensity m) | |
MonadState s m => MonadState s (MaybeT m) | |
MonadState s m => MonadState s (ListT m) | |
(Functor f, MonadState s m) => MonadState s (FreeT f m) | |
(Monoid w, MonadState s m) => MonadState s (WriterT w m) | |
(Monoid w, MonadState s m) => MonadState s (WriterT w m) | |
Monad m => MonadState s (StateT s m) | |
Monad m => MonadState s (StateT s m) | |
MonadState s m => MonadState s (IdentityT * m) | |
MonadState s m => MonadState s (ExceptT e m) | |
(Error e, MonadState s m) => MonadState s (ErrorT e m) | |
MonadState s m => MonadState s (RandT g m) | |
MonadState s m => MonadState s (ReaderT * r m) | |
MonadState s m => MonadState s (ContT * r m) | |
(Monad m, Monoid w) => MonadState s (RWST r w s m) | |
(Monad m, Monoid w) => MonadState s (RWST r w s m) | |
MonadState s m => MonadState s (Proxy a' a b' b m) | |
lift :: MonadTrans t => forall m a. Monad m => m a -> t m a #
Lift a computation from the argument monad to the constructed monad.
type State s = StateT s Identity #
A state monad parameterized by the type s
of the state to carry.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
data StateT s m a :: * -> (* -> *) -> * -> * #
A state transformer monad parameterized by:
s
- The state.m
- The inner monad.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
:: State s a | state-passing computation to execute |
-> s | initial state |
-> (a, s) | return value and final state |
Unwrap a state monad computation as a function.
(The inverse of state
.)
:: State s a | state-passing computation to execute |
-> s | initial value |
-> a | return value of the state computation |
:: State s a | state-passing computation to execute |
-> s | initial value |
-> s | final state |
evalStateT :: Monad m => StateT s m a -> s -> m a #
Evaluate a state computation with the given initial state and return the final value, discarding the final state.
evalStateT
m s =liftM
fst
(runStateT
m s)
execStateT :: Monad m => StateT s m a -> s -> m s #
Evaluate a state computation with the given initial state and return the final state, discarding the final value.
execStateT
m s =liftM
snd
(runStateT
m s)
data WriterT w m a :: * -> (* -> *) -> * -> * #
A writer monad parameterized by:
w
- the output to accumulate.m
- The inner monad.
The return
function produces the output mempty
, while >>=
combines the outputs of the subcomputations using mappend
.
runWriter :: Writer w a -> (a, w) #
Unwrap a writer computation as a (result, output) pair.
(The inverse of writer
.)
execWriter :: Writer w a -> w #
Extract the output from a writer computation.
execWriter
m =snd
(runWriter
m)
runWriterT :: WriterT w m a -> m (a, w) #
execWriterT :: Monad m => WriterT w m a -> m w #
Extract the output from a writer computation.
execWriterT
m =liftM
snd
(runWriterT
m)
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a #
The least element of a non-empty structure with respect to the given comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a #
The largest element of a non-empty structure with respect to the given comparison function.
foldl' :: Foldable t => forall b a. (b -> a -> b) -> b -> t a -> b #
Left-associative fold of a structure but with strict application of the operator.
This ensures that each step of the fold is forced to weak head normal
form before being applied, avoiding the collection of thunks that would
otherwise occur. This is often what you want to strictly reduce a finite
list to a single, monolithic result (e.g. length
).
For a general Foldable
structure this should be semantically identical
to,
foldl f z =foldl'
f z .toList
intercalate :: [a] -> [[a]] -> [a] #
intercalate
xs xss
is equivalent to (
.
It inserts the list concat
(intersperse
xs xss))xs
in between the lists in xss
and concatenates the
result.
catMaybes :: [Maybe a] -> [a] #
The catMaybes
function takes a list of Maybe
s and returns
a list of all the Just
values.
Examples
Basic usage:
>>>
catMaybes [Just 1, Nothing, Just 3]
[1,3]
When constructing a list of Maybe
values, catMaybes
can be used
to return all of the "success" results (if the list is the result
of a map
, then mapMaybe
would be more appropriate):
>>>
import Text.Read ( readMaybe )
>>>
[readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[Just 1,Nothing,Just 3]>>>
catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]
[1,3]
fromMaybe :: a -> Maybe a -> a #
The fromMaybe
function takes a default value and and Maybe
value. If the Maybe
is Nothing
, it returns the default values;
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
getDirectoryContents :: FilePath -> IO [FilePath] #
Similar to listDirectory
, but always includes the special entries (.
and ..
). (This applies to Windows as well.)
The operation may fail with the same exceptions as listDirectory
.
Computation getArgs
returns a list of the program's command
line arguments (not including the program name).
(</>) :: FilePath -> FilePath -> FilePath infixr 5 #
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
will access the same file as
</>
file)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 -> String -> FilePath infixr 7 #
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"
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r #
opens a file using withFile
name mode actopenFile
and passes
the resulting handle to the computation act
. The handle will be
closed on exit from withFile
, whether by normal termination or by
raising an exception. If closing the handle raises an exception, then
this exception will be raised by withFile
rather than any exception
raised by act
.
See openFile
hPutStr :: Handle -> String -> IO () #
Computation hPutStr
hdl s
writes the string
s
to the file or channel managed by hdl
.
This operation may fail with:
isFullError
if the device is full; orisPermissionError
if another system resource limit would be exceeded.
printf :: PrintfType r => String -> r #
Format a variable number of arguments with the C-style formatting string.
The return value is either String
or (
(which
should be IO
a)(
, but Haskell's type system
makes this hard).IO
'()')
The format string consists of ordinary characters and
conversion specifications, which specify how to format
one of the arguments to printf
in the output string. A
format specification is introduced by the %
character;
this character can be self-escaped into the format string
using %%
. A format specification ends with a /format
character/ that provides the primary information about
how to format the value. The rest of the conversion
specification is optional. In order, one may have flag
characters, a width specifier, a precision specifier, and
type-specific modifier characters.
Unlike C printf(3)
, the formatting of this printf
is driven by the argument type; formatting is type specific. The
types formatted by printf
"out of the box" are:
printf
is also extensible to support other types: see below.
A conversion specification begins with the
character %
, followed by zero or more of the following flags:
- left adjust (default is right adjust) + always use a sign (+ or -) for signed conversions space leading space for positive numbers in signed conversions 0 pad with zeros rather than spaces # use an \"alternate form\": see below
When both flags are given, -
overrides 0
and +
overrides space.
A negative width specifier in a *
conversion is treated as
positive but implies the left adjust flag.
The "alternate form" for unsigned radix conversions is
as in C printf(3)
:
%o prefix with a leading 0 if needed %x prefix with a leading 0x if nonzero %X prefix with a leading 0X if nonzero %b prefix with a leading 0b if nonzero %[eEfFgG] ensure that the number contains a decimal point
Any flags are followed optionally by a field width:
num field width * as num, but taken from argument list
The field width is a minimum, not a maximum: it will be expanded as needed to avoid mutilating a value.
Any field width is followed optionally by a precision:
.num precision . same as .0 .* as num, but taken from argument list
Negative precision is taken as 0. The meaning of the precision depends on the conversion type.
Integral minimum number of digits to show RealFloat number of digits after the decimal point String maximum number of characters
The precision for Integral types is accomplished by zero-padding. If both precision and zero-pad are given for an Integral field, the zero-pad is ignored.
Any precision is followed optionally for Integral types by a width modifier; the only use of this modifier being to set the implicit size of the operand for conversion of a negative operand to unsigned:
hh Int8 h Int16 l Int32 ll Int64 L Int64
The specification ends with a format character:
c character Integral d decimal Integral o octal Integral x hexadecimal Integral X hexadecimal Integral b binary Integral u unsigned decimal Integral f floating point RealFloat F floating point RealFloat g general format float RealFloat G general format float RealFloat e exponent format float RealFloat E exponent format float RealFloat s string String v default format any type
The "%v" specifier is provided for all built-in types, and should be provided for user-defined type formatters as well. It picks a "best" representation for the given type. For the built-in types the "%v" specifier is converted as follows:
c Char u other unsigned Integral d other signed Integral g RealFloat s String
Mismatch between the argument types and the format string, as well as any other syntactic or semantic errors in the format string, will cause an exception to be thrown at runtime.
Note that the formatting for RealFloat
types is
currently a bit different from that of C printf(3)
,
conforming instead to showEFloat
,
showFFloat
and showGFloat
(and their
alternate versions showFFloatAlt
and
showGFloatAlt
). This is hard to fix: the fixed
versions would format in a backward-incompatible way.
In any case the Haskell behavior is generally more
sensible than the C behavior. A brief summary of some
key differences:
- Haskell
printf
never uses the default "6-digit" precision used by C printf. - Haskell
printf
treats the "precision" specifier as indicating the number of digits after the decimal point. - Haskell
printf
prints the exponent of e-format numbers without a gratuitous plus sign, and with the minimum possible number of digits. - Haskell
printf
will place a zero after a decimal point when possible.
Examples
> printf "%d\n" (23::Int) 23 > printf "%s %s\n" "Hello" "World" Hello World > printf "%.2f\n" pi 3.14