Movatterモバイル変換
[0]ホーム
{-# LANGUAGE Trustworthy #-}{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}{-# LANGUAGE BangPatterns #-}------------------------------------------------------------------------------- |-- Module : GHC.List-- Copyright : (c) The University of Glasgow 1994-2002-- License : see libraries/base/LICENSE---- Maintainer : cvs-ghc@haskell.org-- Stability : internal-- Portability : non-portable (GHC Extensions)---- The List data type and its operations-------------------------------------------------------------------------------moduleGHC.List(-- [] (..), -- built-in syntax; can't be used in export listmap,(++),filter,concat,head,last,tail,init,uncons,null,length,(!!),foldl,foldl',foldl1,foldl1',scanl,scanl1,scanl',foldr,foldr1,scanr,scanr1,iterate,iterate',repeat,replicate,cycle,take,drop,sum,product,maximum,minimum,splitAt,takeWhile,dropWhile,span,break,reverse,and,or,any,all,elem,notElem,lookup,concatMap,zip,zip3,zipWith,zipWith3,unzip,unzip3,errorEmptyList,)whereimportData.MaybeimportGHC.BaseimportGHC.Num(Num(..))importGHC.Integer(Integer)infixl9!!infix4`elem`,`notElem`---------------------------------------------------------------- List-manipulation functions---------------------------------------------------------------- | Extract the first element of a list, which must be non-empty.head::[a]->ahead(x:_)=xhead[]=badHead{-# NOINLINE[1]head#-}badHead::abadHead=errorEmptyList"head"-- This rule is useful in cases like-- head [y | (x,y) <- ps, x==t]{-# RULES"head/build"forall(g::forallb.(a->b->b)->b->b).head(buildg)=g(\x_->x)badHead"head/augment"forallxs(g::forallb.(a->b->b)->b->b).head(augmentgxs)=g(\x_->x)(headxs)#-}-- | Decompose a list into its head and tail. If the list is empty,-- returns 'Nothing'. If the list is non-empty, returns @'Just' (x, xs)@,-- where @x@ is the head of the list and @xs@ its tail.---- @since 4.8.0.0uncons::[a]->Maybe(a,[a])uncons[]=Nothinguncons(x:xs)=Just(x,xs)-- | Extract the elements after the head of a list, which must be non-empty.tail::[a]->[a]tail(_:xs)=xstail[]=errorEmptyList"tail"-- | Extract the last element of a list, which must be finite and non-empty.last::[a]->a#if defined(USE_REPORT_PRELUDE)last[x]=xlast(_:xs)=lastxslast[]=errorEmptyList"last"#else-- Use foldl to make last a good consumer.-- This will compile to good code for the actual GHC.List.last.-- (At least as long it is eta-expaned, otherwise it does not, #10260.)lastxs=foldl(\_x->x)lastErrorxs{-# INLINElast#-}-- The inline pragma is required to make GHC remember the implementation via-- foldl.lastError::alastError=errorEmptyList"last"#endif-- | Return all the elements of a list except the last one.-- The list must be non-empty.init::[a]->[a]#if defined(USE_REPORT_PRELUDE)init[x]=[]init(x:xs)=x:initxsinit[]=errorEmptyList"init"#else-- eliminate repeated casesinit[]=errorEmptyList"init"init(x:xs)=init'xxswhereinit'_[]=[]init'y(z:zs)=y:init'zzs#endif-- | Test whether a list is empty.null::[a]->Boolnull[]=Truenull(_:_)=False-- | /O(n)/. 'length' returns the length of a finite list as an 'Int'.-- It is an instance of the more general 'Data.List.genericLength',-- the result type of which may be any kind of number.{-# NOINLINE[1]length#-}length::[a]->Intlengthxs=lenAccxs0lenAcc::[a]->Int->IntlenAcc[]n=nlenAcc(_:ys)n=lenAccys(n+1){-# RULES"length"[~1]forallxs.lengthxs=foldrlengthFBidLengthxs0"lengthList"[1]foldrlengthFBidLength=lenAcc#-}-- The lambda form turns out to be necessary to make this inline-- when we need it to and give good performance.{-# INLINE[0]lengthFB#-}lengthFB::x->(Int->Int)->Int->IntlengthFB_r=\!a->r(a+1){-# INLINE[0]idLength#-}idLength::Int->IntidLength=id-- | 'filter', applied to a predicate and a list, returns the list of-- those elements that satisfy the predicate; i.e.,---- > filter p xs = [ x | x <- xs, p x]{-# NOINLINE[1]filter#-}filter::(a->Bool)->[a]->[a]filter_pred[]=[]filterpred(x:xs)|predx=x:filterpredxs|otherwise=filterpredxs{-# INLINE[0]filterFB#-}-- See Note [Inline FB functions]filterFB::(a->b->b)->(a->Bool)->a->b->bfilterFBcpxr|px=x`c`r|otherwise=r{-# RULES"filter"[~1]forallpxs.filterpxs=build(\cn->foldr(filterFBcp)nxs)"filterList"[1]forallp.foldr(filterFB(:)p)[]=filterp"filterFB"forallcpq.filterFB(filterFBcp)q=filterFBc(\x->qx&&px)#-}-- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.-- filterFB (filterFB c p) q a b-- = if q a then filterFB c p a b else b-- = if q a then (if p a then c a b else b) else b-- = if q a && p a then c a b else b-- = filterFB c (\x -> q x && p x) a b-- I originally wrote (\x -> p x && q x), which is wrong, and actually-- gave rise to a live bug report. SLPJ.-- | 'foldl', applied to a binary operator, a starting value (typically-- the left-identity of the operator), and a list, reduces the list-- using the binary operator, from left to right:---- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn---- The list must be finite.foldl::forallab.(b->a->b)->b->[a]->b{-# INLINEfoldl#-}foldlkz0xs=foldr(\(v::a)(fn::b->b)->oneShot(\(z::b)->fn(kzv)))(id::b->b)xsz0-- See Note [Left folds via right fold]{-Note [Left folds via right fold]Implementing foldl et. al. via foldr is only a good idea if the compiler canoptimize the resulting code (eta-expand the recursive "go"). See #7994.We hope that one of the two measure kick in: * Call Arity (-fcall-arity, enabled by default) eta-expands it if it can see all calls and determine that the arity is large. * The oneShot annotation gives a hint to the regular arity analysis that it may assume that the lambda is called at most once. See [One-shot lambdas] in CoreArity and especially [Eta expanding thunks] in CoreArity.The oneShot annotations used in this module are correct, as we only use them inarguments to foldr, where we know how the arguments are called.Note [Inline FB functions]~~~~~~~~~~~~~~~~~~~~~~~~~~After fusion rules successfully fire, we are usually left with one or more callsto list-producing functions abstracted over cons and nil. Here we call themFB functions because their names usually end with 'FB'. It's a good idea toinline FB functions because:* They are higher-order functions and therefore benefits from inlining.* When the final consumer is a left fold, inlining the FB functions is the only way to make arity expansion to happen. See Note [Left fold via right fold].For this reason we mark all FB functions INLINE [0]. The [0] phase-specifierensures that calls to FB functions can be written back to the original formwhen no fusion happens.Without these inline pragmas, the loop in perf/should_run/T13001 won't beallocation-free. Also see Trac #13001.-}-- ------------------------------------------------------------------------------ | A strict version of 'foldl'.foldl'::forallab.(b->a->b)->b->[a]->b{-# INLINEfoldl'#-}foldl'kz0xs=foldr(\(v::a)(fn::b->b)->oneShot(\(z::b)->z`seq`fn(kzv)))(id::b->b)xsz0-- See Note [Left folds via right fold]-- | 'foldl1' is a variant of 'foldl' that has no starting value argument,-- and thus must be applied to non-empty lists.foldl1::(a->a->a)->[a]->afoldl1f(x:xs)=foldlfxxsfoldl1_[]=errorEmptyList"foldl1"-- | A strict version of 'foldl1'foldl1'::(a->a->a)->[a]->afoldl1'f(x:xs)=foldl'fxxsfoldl1'_[]=errorEmptyList"foldl1'"-- ------------------------------------------------------------------------------- List sum and product-- | The 'sum' function computes the sum of a finite list of numbers.sum::(Numa)=>[a]->a{-# INLINEsum#-}sum=foldl(+)0-- | The 'product' function computes the product of a finite list of numbers.product::(Numa)=>[a]->a{-# INLINEproduct#-}product=foldl(*)1-- | 'scanl' is similar to 'foldl', but returns a list of successive-- reduced values from the left:---- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]---- Note that---- > last (scanl f z xs) == foldl f z xs.-- This peculiar arrangement is necessary to prevent scanl being rewritten in-- its own right-hand side.{-# NOINLINE[1]scanl#-}scanl::(b->a->b)->b->[a]->[b]scanl=scanlGowherescanlGo::(b->a->b)->b->[a]->[b]scanlGofqls=q:(caselsof[]->[]x:xs->scanlGof(fqx)xs)-- Note [scanl rewrite rules]{-# RULES"scanl"[~1]forallfabs.scanlfabs=build(\cn->a`c`foldr(scanlFBfc)(constScanln)bsa)"scanlList"[1]forallf(a::a)bs.foldr(scanlFBf(:))(constScanl[])bsa=tail(scanlfabs)#-}{-# INLINE[0]scanlFB#-}-- See Note [Inline FB functions]scanlFB::(b->a->b)->(b->c->c)->a->(b->c)->b->cscanlFBfc=\bg->oneShot(\x->letb'=fxbinb'`c`gb')-- See Note [Left folds via right fold]{-# INLINE[0]constScanl#-}constScanl::a->b->aconstScanl=const-- | 'scanl1' is a variant of 'scanl' that has no starting value argument:---- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]scanl1::(a->a->a)->[a]->[a]scanl1f(x:xs)=scanlfxxsscanl1_[]=[]-- | A strictly accumulating version of 'scanl'{-# NOINLINE[1]scanl'#-}scanl'::(b->a->b)->b->[a]->[b]-- This peculiar form is needed to prevent scanl' from being rewritten-- in its own right hand side.scanl'=scanlGo'wherescanlGo'::(b->a->b)->b->[a]->[b]scanlGo'f!qls=q:(caselsof[]->[]x:xs->scanlGo'f(fqx)xs)-- Note [scanl rewrite rules]{-# RULES"scanl'"[~1]forallfabs.scanl'fabs=build(\cn->a`c`foldr(scanlFB'fc)(flipSeqScanl'n)bsa)"scanlList'"[1]forallfabs.foldr(scanlFB'f(:))(flipSeqScanl'[])bsa=tail(scanl'fabs)#-}{-# INLINE[0]scanlFB'#-}-- See Note [Inline FB functions]scanlFB'::(b->a->b)->(b->c->c)->a->(b->c)->b->cscanlFB'fc=\bg->oneShot(\x->let!b'=fxbinb'`c`gb')-- See Note [Left folds via right fold]{-# INLINE[0]flipSeqScanl'#-}flipSeqScanl'::a->b->aflipSeqScanl'a!_b=a{-Note [scanl rewrite rules]~~~~~~~~~~~~~~~~~~~~~~~~~~In most cases, when we rewrite a form to one that can fuse, we try to rewrite itback to the original form if it does not fuse. For scanl, we do something alittle different. In particular, we rewritescanl f a bstobuild (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)When build is inlined, this becomesa : foldr (scanlFB f (:)) (constScanl []) bs aTo rewrite this form back to scanl, we would need a rule that looked likeforall f a bs. a : foldr (scanlFB f (:)) (constScanl []) bs a = scanl f a bsThe problem with this rule is that it has (:) at its head. This would have theeffect of changing the way the inliner looks at (:), not only here buteverywhere. In most cases, this makes no difference, but in some cases itcauses it to come to a different decision about whether to inline something.Based on nofib benchmarks, this is bad for performance. Therefore, we insteadmatch on everything past the :, which is just the tail of scanl.-}-- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the-- above functions.-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,-- and thus must be applied to non-empty lists.foldr1::(a->a->a)->[a]->afoldr1f=gowherego[x]=xgo(x:xs)=fx(goxs)go[]=errorEmptyList"foldr1"{-# INLINE[0]foldr1#-}-- | 'scanr' is the right-to-left dual of 'scanl'.-- Note that---- > head (scanr f z xs) == foldr f z xs.{-# NOINLINE[1]scanr#-}scanr::(a->b->b)->b->[a]->[b]scanr_q0[]=[q0]scanrfq0(x:xs)=fxq:qswhereqs@(q:_)=scanrfq0xs{-# INLINE[0]strictUncurryScanr#-}strictUncurryScanr::(a->b->c)->(a,b)->cstrictUncurryScanrfpair=casepairof(x,y)->fxy{-# INLINE[0]scanrFB#-}-- See Note [Inline FB functions]scanrFB::(a->b->b)->(b->c->c)->a->(b,c)->(b,c)scanrFBfc=\x(r,est)->(fxr,r`c`est){-# RULES"scanr"[~1]forallfq0ls.scanrfq0ls=build(\cn->strictUncurryScanrc(foldr(scanrFBfc)(q0,n)ls))"scanrList"[1]forallfq0ls.strictUncurryScanr(:)(foldr(scanrFBf(:))(q0,[])ls)=scanrfq0ls#-}-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.scanr1::(a->a->a)->[a]->[a]scanr1_[]=[]scanr1_[x]=[x]scanr1f(x:xs)=fxq:qswhereqs@(q:_)=scanr1fxs-- | 'maximum' returns the maximum value from a list,-- which must be non-empty, finite, and of an ordered type.-- It is a special case of 'Data.List.maximumBy', which allows the-- programmer to supply their own comparison function.maximum::(Orda)=>[a]->a{-# INLINABLEmaximum#-}maximum[]=errorEmptyList"maximum"maximumxs=foldl1maxxs-- We want this to be specialized so that with a strict max function, GHC-- produces good code. Note that to see if this is happending, one has to-- look at -ddump-prep, not -ddump-core!{-# SPECIALIZEmaximum::[Int]->Int#-}{-# SPECIALIZEmaximum::[Integer]->Integer#-}-- | 'minimum' returns the minimum value from a list,-- which must be non-empty, finite, and of an ordered type.-- It is a special case of 'Data.List.minimumBy', which allows the-- programmer to supply their own comparison function.minimum::(Orda)=>[a]->a{-# INLINABLEminimum#-}minimum[]=errorEmptyList"minimum"minimumxs=foldl1minxs{-# SPECIALIZEminimum::[Int]->Int#-}{-# SPECIALIZEminimum::[Integer]->Integer#-}-- | 'iterate' @f x@ returns an infinite list of repeated applications-- of @f@ to @x@:---- > iterate f x == [x, f x, f (f x), ...]---- Note that 'iterate' is lazy, potentially leading to thunk build-up if-- the consumer doesn't force each iterate. See 'iterate\'' for a strict-- variant of this function.{-# NOINLINE[1]iterate#-}iterate::(a->a)->a->[a]iteratefx=x:iteratef(fx){-# INLINE[0]iterateFB#-}-- See Note [Inline FB functions]iterateFB::(a->b->b)->(a->a)->a->biterateFBcfx0=gox0wheregox=x`c`go(fx){-# RULES"iterate"[~1]forallfx.iteratefx=build(\c_n->iterateFBcfx)"iterateFB"[1]iterateFB(:)=iterate#-}-- | 'iterate\'' is the strict version of 'iterate'.---- It ensures that the result of each application of force to weak head normal-- form before proceeding.{-# NOINLINE[1]iterate'#-}iterate'::(a->a)->a->[a]iterate'fx=letx'=fxinx'`seq`(x:iterate'fx'){-# INLINE[0]iterate'FB#-}-- See Note [Inline FB functions]iterate'FB::(a->b->b)->(a->a)->a->biterate'FBcfx0=gox0wheregox=letx'=fxinx'`seq`(x`c`gox'){-# RULES"iterate'"[~1]forallfx.iterate'fx=build(\c_n->iterate'FBcfx)"iterate'FB"[1]iterate'FB(:)=iterate'#-}-- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.repeat::a->[a]{-# INLINE[0]repeat#-}-- The pragma just gives the rules more chance to firerepeatx=xswherexs=x:xs{-# INLINE[0]repeatFB#-}-- ditto -- See Note [Inline FB functions]repeatFB::(a->b->b)->a->brepeatFBcx=xswherexs=x`c`xs{-# RULES"repeat"[~1]forallx.repeatx=build(\c_n->repeatFBcx)"repeatFB"[1]repeatFB(:)=repeat#-}-- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of-- every element.-- It is an instance of the more general 'Data.List.genericReplicate',-- in which @n@ may be of any integral type.{-# INLINEreplicate#-}replicate::Int->a->[a]replicatenx=taken(repeatx)-- | 'cycle' ties a finite list into a circular one, or equivalently,-- the infinite repetition of the original list. It is the identity-- on infinite lists.cycle::[a]->[a]cycle[]=errorEmptyList"cycle"cyclexs=xs'wherexs'=xs++xs'-- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the-- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@:---- > takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]-- > takeWhile (< 9) [1,2,3] == [1,2,3]-- > takeWhile (< 0) [1,2,3] == []--{-# NOINLINE[1]takeWhile#-}takeWhile::(a->Bool)->[a]->[a]takeWhile_[]=[]takeWhilep(x:xs)|px=x:takeWhilepxs|otherwise=[]{-# INLINE[0]takeWhileFB#-}-- See Note [Inline FB functions]takeWhileFB::(a->Bool)->(a->b->b)->b->a->b->btakeWhileFBpcn=\xr->ifpxthenx`c`relsen-- The takeWhileFB rule is similar to the filterFB rule. It works like this:-- takeWhileFB q (takeWhileFB p c n) n =-- \x r -> if q x then (takeWhileFB p c n) x r else n =-- \x r -> if q x then (\x' r' -> if p x' then x' `c` r' else n) x r else n =-- \x r -> if q x then (if p x then x `c` r else n) else n =-- \x r -> if q x && p x then x `c` r else n =-- takeWhileFB (\x -> q x && p x) c n{-# RULES"takeWhile"[~1]forallpxs.takeWhilepxs=build(\cn->foldr(takeWhileFBpcn)nxs)"takeWhileList"[1]forallp.foldr(takeWhileFBp(:)[])[]=takeWhilep"takeWhileFB"forallcnpq.takeWhileFBq(takeWhileFBpcn)n=takeWhileFB(\x->qx&&px)cn#-}-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@:---- > dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]-- > dropWhile (< 9) [1,2,3] == []-- > dropWhile (< 0) [1,2,3] == [1,2,3]--dropWhile::(a->Bool)->[a]->[a]dropWhile_[]=[]dropWhilepxs@(x:xs')|px=dropWhilepxs'|otherwise=xs-- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@-- of length @n@, or @xs@ itself if @n > 'length' xs@:---- > take 5 "Hello World!" == "Hello"-- > take 3 [1,2,3,4,5] == [1,2,3]-- > take 3 [1,2] == [1,2]-- > take 3 [] == []-- > take (-1) [1,2] == []-- > take 0 [1,2] == []---- It is an instance of the more general 'Data.List.genericTake',-- in which @n@ may be of any integral type.take::Int->[a]->[a]#if defined(USE_REPORT_PRELUDE)taken_|n<=0=[]take_[]=[]taken(x:xs)=x:take(n-1)xs#else{- We always want to inline this to take advantage of a known length argumentsign. Note, however, that it's important for the RULES to grab take, ratherthan trying to INLINE take immediately and then letting the RULES grabunsafeTake. Presumably the latter approach doesn't grab it early enough; it ledto an allocation regression in nofib/fft2. -}{-# INLINE[1]take#-}takenxs|0<n=unsafeTakenxs|otherwise=[]-- A version of take that takes the whole list if it's given an argument less-- than 1.{-# NOINLINE[1]unsafeTake#-}unsafeTake::Int->[a]->[a]unsafeTake!_[]=[]unsafeTake1(x:_)=[x]unsafeTakem(x:xs)=x:unsafeTake(m-1)xs{-# RULES"take"[~1]forallnxs.takenxs=build(\cnil->if0<nthenfoldr(takeFBcnil)(flipSeqTakenil)xsnelsenil)"unsafeTakeList"[1]forallnxs.foldr(takeFB(:)[])(flipSeqTake[])xsn=unsafeTakenxs#-}{-# INLINE[0]flipSeqTake#-}-- Just flip seq, specialized to Int, but not inlined too early.-- It's important to force the numeric argument here, even though-- it's not used. Otherwise, take n [] doesn't force n. This is-- bad for strictness analysis and unboxing, and leads to increased-- allocation in T7257.flipSeqTake::a->Int->aflipSeqTakex!_n=x{-# INLINE[0]takeFB#-}-- See Note [Inline FB functions]takeFB::(a->b->b)->b->a->(Int->b)->Int->b-- The \m accounts for the fact that takeFB is used in a higher-order-- way by takeFoldr, so it's better to inline. A good example is-- take n (repeat x)-- for which we get excellent code... but only if we inline takeFB-- when given four argumentstakeFBcnxxs=\m->casemof1->x`c`n_->x`c`xs(m-1)#endif-- | 'drop' @n xs@ returns the suffix of @xs@-- after the first @n@ elements, or @[]@ if @n > 'length' xs@:---- > drop 6 "Hello World!" == "World!"-- > drop 3 [1,2,3,4,5] == [4,5]-- > drop 3 [1,2] == []-- > drop 3 [] == []-- > drop (-1) [1,2] == [1,2]-- > drop 0 [1,2] == [1,2]---- It is an instance of the more general 'Data.List.genericDrop',-- in which @n@ may be of any integral type.drop::Int->[a]->[a]#if defined(USE_REPORT_PRELUDE)dropnxs|n<=0=xsdrop_[]=[]dropn(_:xs)=drop(n-1)xs#else /* hack away */{-# INLINEdrop#-}dropnls|n<=0=ls|otherwise=unsafeDropnlswhere-- A version of drop that drops the whole list if given an argument-- less than 1unsafeDrop::Int->[a]->[a]unsafeDrop!_[]=[]unsafeDrop1(_:xs)=xsunsafeDropm(_:xs)=unsafeDrop(m-1)xs#endif-- | 'splitAt' @n xs@ returns a tuple where first element is @xs@ prefix of-- length @n@ and second element is the remainder of the list:---- > splitAt 6 "Hello World!" == ("Hello ","World!")-- > splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])-- > splitAt 1 [1,2,3] == ([1],[2,3])-- > splitAt 3 [1,2,3] == ([1,2,3],[])-- > splitAt 4 [1,2,3] == ([1,2,3],[])-- > splitAt 0 [1,2,3] == ([],[1,2,3])-- > splitAt (-1) [1,2,3] == ([],[1,2,3])---- It is equivalent to @('take' n xs, 'drop' n xs)@ when @n@ is not @_|_@-- (@splitAt _|_ xs = _|_@).-- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt',-- in which @n@ may be of any integral type.splitAt::Int->[a]->([a],[a])#if defined(USE_REPORT_PRELUDE)splitAtnxs=(takenxs,dropnxs)#elsesplitAtnls|n<=0=([],ls)|otherwise=splitAt'nlswheresplitAt'::Int->[a]->([a],[a])splitAt'_[]=([],[])splitAt'1(x:xs)=([x],xs)splitAt'm(x:xs)=(x:xs',xs'')where(xs',xs'')=splitAt'(m-1)xs#endif /* USE_REPORT_PRELUDE */-- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where-- first element is longest prefix (possibly empty) of @xs@ of elements that-- satisfy @p@ and second element is the remainder of the list:---- > span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])-- > span (< 9) [1,2,3] == ([1,2,3],[])-- > span (< 0) [1,2,3] == ([],[1,2,3])---- 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@span::(a->Bool)->[a]->([a],[a])span_xs@[]=(xs,xs)spanpxs@(x:xs')|px=let(ys,zs)=spanpxs'in(x:ys,zs)|otherwise=([],xs)-- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where-- first element is longest prefix (possibly empty) of @xs@ of elements that-- /do not satisfy/ @p@ and second element is the remainder of the list:---- > break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])-- > break (< 9) [1,2,3] == ([],[1,2,3])-- > break (> 9) [1,2,3] == ([1,2,3],[])---- 'break' @p@ is equivalent to @'span' ('not' . p)@.break::(a->Bool)->[a]->([a],[a])#if defined(USE_REPORT_PRELUDE)breakp=span(not.p)#else-- HBC version (stolen)break_xs@[]=(xs,xs)breakpxs@(x:xs')|px=([],xs)|otherwise=let(ys,zs)=breakpxs'in(x:ys,zs)#endif-- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.-- @xs@ must be finite.reverse::[a]->[a]#if defined(USE_REPORT_PRELUDE)reverse=foldl(flip(:))[]#elsereversel=revl[]whererev[]a=arev(x:xs)a=revxs(x:a)#endif-- | 'and' returns the conjunction of a Boolean list. For the result to be-- 'True', the list must be finite; 'False', however, results from a 'False'-- value at a finite index of a finite or infinite list.and::[Bool]->Bool#if defined(USE_REPORT_PRELUDE)and=foldr(&&)True#elseand[]=Trueand(x:xs)=x&&andxs{-# NOINLINE[1]and#-}{-# RULES"and/build"forall(g::forallb.(Bool->b->b)->b->b).and(buildg)=g(&&)True#-}#endif-- | 'or' returns the disjunction of a Boolean list. For the result to be-- 'False', the list must be finite; 'True', however, results from a 'True'-- value at a finite index of a finite or infinite list.or::[Bool]->Bool#if defined(USE_REPORT_PRELUDE)or=foldr(||)False#elseor[]=Falseor(x:xs)=x||orxs{-# NOINLINE[1]or#-}{-# RULES"or/build"forall(g::forallb.(Bool->b->b)->b->b).or(buildg)=g(||)False#-}#endif-- | Applied to a predicate and a list, 'any' determines if any element-- of the list satisfies the predicate. For the result to be-- 'False', the list must be finite; 'True', however, results from a 'True'-- value for the predicate applied to an element at a finite index of a finite or infinite list.any::(a->Bool)->[a]->Bool#if defined(USE_REPORT_PRELUDE)anyp=or.mapp#elseany_[]=Falseanyp(x:xs)=px||anypxs{-# NOINLINE[1]any#-}{-# RULES"any/build"forallp(g::forallb.(a->b->b)->b->b).anyp(buildg)=g((||).p)False#-}#endif-- | Applied to a predicate and a list, 'all' determines if all elements-- of the list satisfy the predicate. For the result to be-- 'True', the list must be finite; 'False', however, results from a 'False'-- value for the predicate applied to an element at a finite index of a finite or infinite list.all::(a->Bool)->[a]->Bool#if defined(USE_REPORT_PRELUDE)allp=and.mapp#elseall_[]=Trueallp(x:xs)=px&&allpxs{-# NOINLINE[1]all#-}{-# RULES"all/build"forallp(g::forallb.(a->b->b)->b->b).allp(buildg)=g((&&).p)True#-}#endif-- | 'elem' is the list membership predicate, usually written in infix form,-- e.g., @x \`elem\` xs@. For the result to be-- 'False', the list must be finite; 'True', however, results from an element-- equal to @x@ found at a finite index of a finite or infinite list.elem::(Eqa)=>a->[a]->Bool#if defined(USE_REPORT_PRELUDE)elemx=any(==x)#elseelem_[]=Falseelemx(y:ys)=x==y||elemxys{-# NOINLINE[1]elem#-}{-# RULES"elem/build"forallx(g::forallb.Eqa=>(a->b->b)->b->b).elemx(buildg)=g(\yr->(x==y)||r)False#-}#endif-- | 'notElem' is the negation of 'elem'.notElem::(Eqa)=>a->[a]->Bool#if defined(USE_REPORT_PRELUDE)notElemx=all(/=x)#elsenotElem_[]=TruenotElemx(y:ys)=x/=y&¬Elemxys{-# NOINLINE[1]notElem#-}{-# RULES"notElem/build"forallx(g::forallb.Eqa=>(a->b->b)->b->b).notElemx(buildg)=g(\yr->(x/=y)&&r)True#-}#endif-- | 'lookup' @key assocs@ looks up a key in an association list.lookup::(Eqa)=>a->[(a,b)]->Maybeblookup_key[]=Nothinglookupkey((x,y):xys)|key==x=Justy|otherwise=lookupkeyxys-- | Map a function over a list and concatenate the results.concatMap::(a->[b])->[a]->[b]concatMapf=foldr((++).f)[]{-# NOINLINE[1]concatMap#-}{-# RULES"concatMap"forallfxs.concatMapfxs=build(\cn->foldr(\xb->foldrcb(fx))nxs)#-}-- | Concatenate a list of lists.concat::[[a]]->[a]concat=foldr(++)[]{-# NOINLINE[1]concat#-}{-# RULES"concat"forallxs.concatxs=build(\cn->foldr(\xy->foldrcyx)nxs)-- We don't bother to turn non-fusible applications of concat back into concat#-}-- | List index (subscript) operator, starting from 0.-- It is an instance of the more general 'Data.List.genericIndex',-- which takes an index of any integral type.(!!)::[a]->Int->a#if defined(USE_REPORT_PRELUDE)xs!!n|n<0=errorWithoutStackTrace"Prelude.!!: negative index"[]!!_=errorWithoutStackTrace"Prelude.!!: index too large"(x:_)!!0=x(_:xs)!!n=xs!!(n-1)#else-- We don't really want the errors to inline with (!!).-- We may want to fuss around a bit with NOINLINE, and-- if so we should be careful not to trip up known-bottom-- optimizations.tooLarge::Int->atooLarge_=errorWithoutStackTrace(prel_list_str++"!!: index too large")negIndex::anegIndex=errorWithoutStackTrace$prel_list_str++"!!: negative index"{-# INLINABLE(!!)#-}xs!!n|n<0=negIndex|otherwise=foldr(\xrk->casekof0->x_->r(k-1))tooLargexsn#endif---------------------------------------------------------------- The zip family--------------------------------------------------------------foldr2::(a->b->c->c)->c->[a]->[b]->cfoldr2kz=gowherego[]_ys=zgo_xs[]=zgo(x:xs)(y:ys)=kxy(goxsys){-# INLINE[0]foldr2#-}foldr2_left::(a->b->c->d)->d->a->([b]->c)->[b]->dfoldr2_left_kz_x_r[]=zfoldr2_leftk_zxr(y:ys)=kxy(rys)-- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys{-# RULES"foldr2/left"forallkzys(g::forallb.(a->b->b)->b->b).foldr2kz(buildg)ys=g(foldr2_leftkz)(\_->z)ys#-}-- There used to be a foldr2/right rule, allowing foldr2 to fuse with a build-- form on the right. However, this causes trouble if the right list ends in-- a bottom that is only avoided by the left list ending at that spot. That is,-- foldr2 f z [a,b,c] (d:e:f:_|_), where the right list is produced by a build-- form, would cause the foldr2/right rule to introduce bottom. Example:---- zip [1,2,3,4] (unfoldr (\s -> if s > 4 then undefined else Just (s,s+1)) 1)---- should produce---- [(1,1),(2,2),(3,3),(4,4)]---- but with the foldr2/right rule it would instead produce---- (1,1):(2,2):(3,3):(4,4):_|_-- Zips for larger tuples are in the List module.------------------------------------------------ | 'zip' takes two lists and returns a list of corresponding pairs.---- > zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]---- If one input list is short, excess elements of the longer list are-- discarded:---- > zip [1] ['a', 'b'] = [(1, 'a')]-- > zip [1, 2] ['a'] = [(1, 'a')]---- 'zip' is right-lazy:---- > zip [] _|_ = []-- > zip _|_ [] = _|_{-# NOINLINE[1]zip#-}zip::[a]->[b]->[(a,b)]zip[]_bs=[]zip_as[]=[]zip(a:as)(b:bs)=(a,b):zipasbs{-# INLINE[0]zipFB#-}-- See Note [Inline FB functions]zipFB::((a,b)->c->d)->a->b->c->dzipFBc=\xyr->(x,y)`c`r{-# RULES"zip"[~1]forallxsys.zipxsys=build(\cn->foldr2(zipFBc)nxsys)"zipList"[1]foldr2(zipFB(:))[]=zip#-}------------------------------------------------ | 'zip3' takes three lists and returns a list of triples, analogous to-- 'zip'.zip3::[a]->[b]->[c]->[(a,b,c)]-- Specification-- zip3 = zipWith3 (,,)zip3(a:as)(b:bs)(c:cs)=(a,b,c):zip3asbscszip3___=[]-- The zipWith family generalises the zip family by zipping with the-- function given as the first argument, instead of a tupling function.------------------------------------------------ | 'zipWith' generalises 'zip' by zipping with the function given-- as the first argument, instead of a tupling function.-- For example, @'zipWith' (+)@ is applied to two lists to produce the-- list of corresponding sums.---- 'zipWith' is right-lazy:---- > zipWith f [] _|_ = []{-# NOINLINE[1]zipWith#-}zipWith::(a->b->c)->[a]->[b]->[c]zipWithf=gowherego[]_=[]go_[]=[]go(x:xs)(y:ys)=fxy:goxsys-- zipWithFB must have arity 2 since it gets two arguments in the "zipWith"-- rule; it might not get inlined otherwise{-# INLINE[0]zipWithFB#-}-- See Note [Inline FB functions]zipWithFB::(a->b->c)->(d->e->a)->d->e->b->czipWithFBcf=\xyr->(x`f`y)`c`r{-# RULES"zipWith"[~1]forallfxsys.zipWithfxsys=build(\cn->foldr2(zipWithFBcf)nxsys)"zipWithList"[1]forallf.foldr2(zipWithFB(:)f)[]=zipWithf#-}-- | The 'zipWith3' function takes a function which combines three-- elements, as well as three lists and returns a list of their point-wise-- combination, analogous to 'zipWith'.zipWith3::(a->b->c->d)->[a]->[b]->[c]->[d]zipWith3z=gowherego(a:as)(b:bs)(c:cs)=zabc:goasbscsgo___=[]-- | 'unzip' transforms a list of pairs into a list of first components-- and a list of second components.unzip::[(a,b)]->([a],[b]){-# INLINEunzip#-}unzip=foldr(\(a,b)~(as,bs)->(a:as,b:bs))([],[])-- | The 'unzip3' function takes a list of triples and returns three-- lists, analogous to 'unzip'.unzip3::[(a,b,c)]->([a],[b],[c]){-# INLINEunzip3#-}unzip3=foldr(\(a,b,c)~(as,bs,cs)->(a:as,b:bs,c:cs))([],[],[])---------------------------------------------------------------- Error code---------------------------------------------------------------- Common up near identical calls to `error' to reduce the number-- constant strings created when compiled:errorEmptyList::String->aerrorEmptyListfun=errorWithoutStackTrace(prel_list_str++fun++": empty list")prel_list_str::Stringprel_list_str="Prelude."
[8]ページ先頭