Movatterモバイル変換


[0]ホーム

URL:


{-# LANGUAGE DeriveFoldable #-}{-# LANGUAGE FlexibleInstances #-}{-# LANGUAGE NoImplicitPrelude #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE StandaloneDeriving #-}{-# LANGUAGE Trustworthy #-}{-# LANGUAGE TypeOperators #-}------------------------------------------------------------------------------- |-- Module      :  Data.Foldable-- Copyright   :  Ross Paterson 2005-- License     :  BSD-style (see the LICENSE file in the distribution)---- Maintainer  :  libraries@haskell.org-- Stability   :  experimental-- Portability :  portable---- Class of data structures that can be folded to a summary value.-------------------------------------------------------------------------------moduleData.Foldable(Foldable(..),-- * Special biased foldsfoldrM,foldlM,-- * Folding actions-- ** Applicative actionstraverse_,for_,sequenceA_,asum,-- ** Monadic actionsmapM_,forM_,sequence_,msum,-- * Specialized foldsconcat,concatMap,and,or,any,all,maximumBy,minimumBy,-- * SearchesnotElem,find)whereimportData.BoolimportData.EitherimportData.EqimportData.Functor.Utils(Max(..),Min(..),(#.))importqualifiedGHC.ListasListimportData.MaybeimportData.MonoidimportData.OrdimportData.ProxyimportGHC.Arr(Array(..),elems,numElements,foldlElems,foldrElems,foldlElems',foldrElems',foldl1Elems,foldr1Elems)importGHC.Basehiding(foldr)importGHC.GenericsimportGHC.Num(Num(..))infix4`elem`,`notElem`-- | Data structures that can be folded.---- For example, given a data type---- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)---- a suitable instance would be---- > instance Foldable Tree where-- >    foldMap f Empty = mempty-- >    foldMap f (Leaf x) = f x-- >    foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r---- This is suitable even for abstract types, as the monoid is assumed-- to satisfy the monoid laws.  Alternatively, one could define @foldr@:---- > instance Foldable Tree where-- >    foldr f z Empty = z-- >    foldr f z (Leaf x) = f x z-- >    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l---- @Foldable@ instances are expected to satisfy the following laws:---- > foldr f z t = appEndo (foldMap (Endo . f) t ) z---- > foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z---- > fold = foldMap id---- > length = getSum . foldMap (Sum . const  1)---- @sum@, @product@, @maximum@, and @minimum@ should all be essentially-- equivalent to @foldMap@ forms, such as---- > sum = getSum . foldMap Sum---- but may be less defined.---- If the type is also a 'Functor' instance, it should satisfy---- > foldMap f = fold . fmap f---- which implies that---- > foldMap f . fmap g = foldMap (f . g)classFoldabletwhere{-# MINIMALfoldMap|foldr#-}-- | Combine the elements of a structure using a monoid.fold::Monoidm=>tm->mfold=foldMapid-- | Map each element of the structure to a monoid,-- and combine the results.foldMap::Monoidm=>(a->m)->ta->m{-# INLINEfoldMap#-}-- This INLINE allows more list functions to fuse. See Trac #9848.foldMapf=foldr(mappend.f)mempty-- | Right-associative fold of a structure.---- In the case of lists, 'foldr', when applied to a binary operator, a-- starting value (typically the right-identity of the operator), and a-- list, reduces the list using the binary operator, from right to left:---- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)---- Note that, since the head of the resulting expression is produced by-- an application of the operator to the first element of the list,-- 'foldr' can produce a terminating expression from an infinite list.---- For a general 'Foldable' structure this should be semantically identical-- to,---- @foldr f z = 'List.foldr' f z . 'toList'@--foldr::(a->b->b)->b->ta->bfoldrfzt=appEndo(foldMap(Endo#.f)t)z-- | Right-associative fold of a structure, but with strict application of-- the operator.--foldr'::(a->b->b)->b->ta->bfoldr'fz0xs=foldlf'idxsz0wheref'kxz=k$!fxz-- | Left-associative fold of a structure.---- In the case of lists, 'foldl', when 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---- Note that to produce the outermost application of the operator the-- entire input list must be traversed. This means that 'foldl'' will-- diverge if given an infinite list.---- Also note that if you want an efficient left-fold, you probably want to-- use 'foldl'' instead of 'foldl'. The reason for this is that latter does-- not force the "inner" results (e.g. @z `f` x1@ in the above example)-- before applying them to the operator (e.g. to @(`f` x2)@). This results-- in a thunk chain @O(n)@ elements long, which then must be evaluated from-- the outside-in.---- For a general 'Foldable' structure this should be semantically identical-- to,---- @foldl f z = 'List.foldl' f z . 'toList'@--foldl::(b->a->b)->b->ta->bfoldlfzt=appEndo(getDual(foldMap(Dual.Endo.flipf)t))z-- There's no point mucking around with coercions here,-- because flip forces us to build a new function anyway.-- | 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 = 'List.foldl'' f z . 'toList'@--foldl'::(b->a->b)->b->ta->bfoldl'fz0xs=foldrf'idxsz0wheref'xkz=k$!fzx-- | A variant of 'foldr' that has no base case,-- and thus may only be applied to non-empty structures.---- @'foldr1' f = 'List.foldr1' f . 'toList'@foldr1::(a->a->a)->ta->afoldr1fxs=fromMaybe(errorWithoutStackTrace"foldr1: empty structure")(foldrmfNothingxs)wheremfxm=Just(casemofNothing->xJusty->fxy)-- | A variant of 'foldl' that has no base case,-- and thus may only be applied to non-empty structures.---- @'foldl1' f = 'List.foldl1' f . 'toList'@foldl1::(a->a->a)->ta->afoldl1fxs=fromMaybe(errorWithoutStackTrace"foldl1: empty structure")(foldlmfNothingxs)wheremfmy=Just(casemofNothing->yJustx->fxy)-- | List of elements of a structure, from left to right.toList::ta->[a]{-# INLINEtoList#-}toListt=build(\cn->foldrcnt)-- | Test whether the structure is empty. The default implementation is-- optimized for structures that are similar to cons-lists, because there-- is no general way to do better.null::ta->Boolnull=foldr(\__->False)True-- | Returns the size/length of a finite structure as an 'Int'.  The-- default implementation is optimized for structures that are similar to-- cons-lists, because there is no general way to do better.length::ta->Intlength=foldl'(\c_->c+1)0-- | Does the element occur in the structure?elem::Eqa=>a->ta->Boolelem=any.(==)-- | The largest element of a non-empty structure.maximum::foralla.Orda=>ta->amaximum=fromMaybe(errorWithoutStackTrace"maximum: empty structure").getMax.foldMap(Max#.(Just::a->Maybea))-- | The least element of a non-empty structure.minimum::foralla.Orda=>ta->aminimum=fromMaybe(errorWithoutStackTrace"minimum: empty structure").getMin.foldMap(Min#.(Just::a->Maybea))-- | The 'sum' function computes the sum of the numbers of a structure.sum::Numa=>ta->asum=getSum#.foldMapSum-- | The 'product' function computes the product of the numbers of a-- structure.product::Numa=>ta->aproduct=getProduct#.foldMapProduct-- instances for Prelude types-- | @since 2.01instanceFoldableMaybewherefoldMap=maybememptyfoldr_zNothing=zfoldrfz(Justx)=fxzfoldl_zNothing=zfoldlfz(Justx)=fzx-- | @since 2.01instanceFoldable[]whereelem=List.elemfoldl=List.foldlfoldl'=List.foldl'foldl1=List.foldl1foldr=List.foldrfoldr1=List.foldr1length=List.lengthmaximum=List.maximumminimum=List.minimumnull=List.nullproduct=List.productsum=List.sumtoList=id-- | @since 4.9.0.0instanceFoldableNonEmptywherefoldrfz~(a:|as)=fa(List.foldrfzas)foldlfz(a:|as)=List.foldlf(fza)asfoldl1f(a:|as)=List.foldlfaas-- GHC isn't clever enough to transform the default definition-- into anything like this, so we'd end up shuffling a bunch of-- Maybes around.foldr1f(p:|ps)=foldrgoidpspwheregoxrprev=fprev(rx)-- We used to say----   length (_ :| as) = 1 + length as---- but the default definition is better, counting from 1.---- The default definition also works great for null and foldl'.-- As usual for cons lists, foldr' is basically hopeless.foldMapf~(a:|as)=fa`mappend`foldMapfasfold~(m:|ms)=m`mappend`foldmstoList~(a:|as)=a:as-- | @since 4.7.0.0instanceFoldable(Eithera)wherefoldMap_(Left_)=memptyfoldMapf(Righty)=fyfoldr_z(Left_)=zfoldrfz(Righty)=fyzlength(Left_)=0length(Right_)=1null=isLeft-- | @since 4.7.0.0instanceFoldable((,)a)wherefoldMapf(_,y)=fyfoldrfz(_,y)=fyz-- | @since 4.8.0.0instanceFoldable(Arrayi)wherefoldr=foldrElemsfoldl=foldlElemsfoldl'=foldlElems'foldr'=foldrElems'foldl1=foldl1Elemsfoldr1=foldr1ElemstoList=elemslength=numElementsnulla=numElementsa==0-- | @since 4.7.0.0instanceFoldableProxywherefoldMap__=mempty{-# INLINEfoldMap#-}fold_=mempty{-# INLINEfold#-}foldr_z_=z{-# INLINEfoldr#-}foldl_z_=z{-# INLINEfoldl#-}foldl1__=errorWithoutStackTrace"foldl1: Proxy"foldr1__=errorWithoutStackTrace"foldr1: Proxy"length_=0null_=Trueelem__=Falsesum_=0product_=1-- | @since 4.8.0.0instanceFoldableDualwherefoldMap=coerceelem=(.getDual)#.(==)foldl=coercefoldl'=coercefoldl1_=getDualfoldrfz(Dualx)=fxzfoldr'=foldrfoldr1_=getDuallength_=1maximum=getDualminimum=getDualnull_=Falseproduct=getDualsum=getDualtoList(Dualx)=[x]-- | @since 4.8.0.0instanceFoldableSumwherefoldMap=coerceelem=(.getSum)#.(==)foldl=coercefoldl'=coercefoldl1_=getSumfoldrfz(Sumx)=fxzfoldr'=foldrfoldr1_=getSumlength_=1maximum=getSumminimum=getSumnull_=Falseproduct=getSumsum=getSumtoList(Sumx)=[x]-- | @since 4.8.0.0instanceFoldableProductwherefoldMap=coerceelem=(.getProduct)#.(==)foldl=coercefoldl'=coercefoldl1_=getProductfoldrfz(Productx)=fxzfoldr'=foldrfoldr1_=getProductlength_=1maximum=getProductminimum=getProductnull_=Falseproduct=getProductsum=getProducttoList(Productx)=[x]-- | @since 4.8.0.0instanceFoldableFirstwherefoldMapf=foldMapf.getFirst-- | @since 4.8.0.0instanceFoldableLastwherefoldMapf=foldMapf.getLast-- | @since 4.12.0.0instance(Foldablef)=>Foldable(Altf)wherefoldMapf=foldMapf.getAlt-- | @since 4.12.0.0instance(Foldablef)=>Foldable(Apf)wherefoldMapf=foldMapf.getAp-- Instances for GHC.Generics-- | @since 4.9.0.0instanceFoldableU1wherefoldMap__=mempty{-# INLINEfoldMap#-}fold_=mempty{-# INLINEfold#-}foldr_z_=z{-# INLINEfoldr#-}foldl_z_=z{-# INLINEfoldl#-}foldl1__=errorWithoutStackTrace"foldl1: U1"foldr1__=errorWithoutStackTrace"foldr1: U1"length_=0null_=Trueelem__=Falsesum_=0product_=1-- | @since 4.9.0.0derivinginstanceFoldableV1-- | @since 4.9.0.0derivinginstanceFoldablePar1-- | @since 4.9.0.0derivinginstanceFoldablef=>Foldable(Rec1f)-- | @since 4.9.0.0derivinginstanceFoldable(K1ic)-- | @since 4.9.0.0derivinginstanceFoldablef=>Foldable(M1icf)-- | @since 4.9.0.0derivinginstance(Foldablef,Foldableg)=>Foldable(f:+:g)-- | @since 4.9.0.0derivinginstance(Foldablef,Foldableg)=>Foldable(f:*:g)-- | @since 4.9.0.0derivinginstance(Foldablef,Foldableg)=>Foldable(f:.:g)-- | @since 4.9.0.0derivinginstanceFoldableUAddr-- | @since 4.9.0.0derivinginstanceFoldableUChar-- | @since 4.9.0.0derivinginstanceFoldableUDouble-- | @since 4.9.0.0derivinginstanceFoldableUFloat-- | @since 4.9.0.0derivinginstanceFoldableUInt-- | @since 4.9.0.0derivinginstanceFoldableUWord-- Instances for Data.Ord-- | @since 4.12.0.0derivinginstanceFoldableDown-- | Monadic fold over the elements of a structure,-- associating to the right, i.e. from right to left.foldrM::(Foldablet,Monadm)=>(a->b->mb)->b->ta->mbfoldrMfz0xs=foldlf'returnxsz0wheref'kxz=fxz>>=k-- | Monadic fold over the elements of a structure,-- associating to the left, i.e. from left to right.foldlM::(Foldablet,Monadm)=>(b->a->mb)->b->ta->mbfoldlMfz0xs=foldrf'returnxsz0wheref'xkz=fzx>>=k-- | Map each element of a structure to an action, evaluate these-- actions from left to right, and ignore the results. For a version-- that doesn't ignore the results see 'Data.Traversable.traverse'.traverse_::(Foldablet,Applicativef)=>(a->fb)->ta->f()traverse_f=foldr((*>).f)(pure())-- | 'for_' is 'traverse_' with its arguments flipped. For a version-- that doesn't ignore the results see 'Data.Traversable.for'.---- >>> for_ [1..4] print-- 1-- 2-- 3-- 4for_::(Foldablet,Applicativef)=>ta->(a->fb)->f(){-# INLINEfor_#-}for_=fliptraverse_-- | Map each element of a structure to a monadic action, evaluate-- these actions from left to right, and ignore the results. For a-- version that doesn't ignore the results see-- 'Data.Traversable.mapM'.---- As of base 4.8.0.0, 'mapM_' is just 'traverse_', specialized to-- 'Monad'.mapM_::(Foldablet,Monadm)=>(a->mb)->ta->m()mapM_f=foldr((>>).f)(return())-- | 'forM_' is 'mapM_' with its arguments flipped. For a version that-- doesn't ignore the results see 'Data.Traversable.forM'.---- As of base 4.8.0.0, 'forM_' is just 'for_', specialized to 'Monad'.forM_::(Foldablet,Monadm)=>ta->(a->mb)->m(){-# INLINEforM_#-}forM_=flipmapM_-- | Evaluate each action in the structure from left to right, and-- ignore the results. For a version that doesn't ignore the results-- see 'Data.Traversable.sequenceA'.sequenceA_::(Foldablet,Applicativef)=>t(fa)->f()sequenceA_=foldr(*>)(pure())-- | Evaluate each monadic action in the structure from left to right,-- and ignore the results. For a version that doesn't ignore the-- results see 'Data.Traversable.sequence'.---- As of base 4.8.0.0, 'sequence_' is just 'sequenceA_', specialized-- to 'Monad'.sequence_::(Foldablet,Monadm)=>t(ma)->m()sequence_=foldr(>>)(return())-- | The sum of a collection of actions, generalizing 'concat'.---- asum [Just "Hello", Nothing, Just "World"]-- Just "Hello"asum::(Foldablet,Alternativef)=>t(fa)->fa{-# INLINEasum#-}asum=foldr(<|>)empty-- | The sum of a collection of actions, generalizing 'concat'.-- As of base 4.8.0.0, 'msum' is just 'asum', specialized to 'MonadPlus'.msum::(Foldablet,MonadPlusm)=>t(ma)->ma{-# INLINEmsum#-}msum=asum-- | The concatenation of all the elements of a container of lists.concat::Foldablet=>t[a]->[a]concatxs=build(\cn->foldr(\xy->foldrcyx)nxs){-# INLINEconcat#-}-- | Map a function over all the elements of a container and concatenate-- the resulting lists.concatMap::Foldablet=>(a->[b])->ta->[b]concatMapfxs=build(\cn->foldr(\xb->foldrcb(fx))nxs){-# INLINEconcatMap#-}-- These use foldr rather than foldMap to avoid repeated concatenation.-- | 'and' returns the conjunction of a container of Bools.  For the-- result to be 'True', the container must be finite; 'False', however,-- results from a 'False' value finitely far from the left end.and::Foldablet=>tBool->Booland=getAll#.foldMapAll-- | 'or' returns the disjunction of a container of Bools.  For the-- result to be 'False', the container must be finite; 'True', however,-- results from a 'True' value finitely far from the left end.or::Foldablet=>tBool->Boolor=getAny#.foldMapAny-- | Determines whether any element of the structure satisfies the predicate.any::Foldablet=>(a->Bool)->ta->Boolanyp=getAny#.foldMap(Any#.p)-- | Determines whether all elements of the structure satisfy the predicate.all::Foldablet=>(a->Bool)->ta->Boolallp=getAll#.foldMap(All#.p)-- | The largest element of a non-empty structure with respect to the-- given comparison function.-- See Note [maximumBy/minimumBy space usage]maximumBy::Foldablet=>(a->a->Ordering)->ta->amaximumBycmp=foldl1max'wheremax'xy=casecmpxyofGT->x_->y-- | The least element of a non-empty structure with respect to the-- given comparison function.-- See Note [maximumBy/minimumBy space usage]minimumBy::Foldablet=>(a->a->Ordering)->ta->aminimumBycmp=foldl1min'wheremin'xy=casecmpxyofGT->y_->x-- | 'notElem' is the negation of 'elem'.notElem::(Foldablet,Eqa)=>a->ta->BoolnotElemx=not.elemx-- | The 'find' function takes a predicate and a structure and returns-- the leftmost element of the structure matching the predicate, or-- 'Nothing' if there is no such element.find::Foldablet=>(a->Bool)->ta->Maybeafindp=getFirst.foldMap(\x->First(ifpxthenJustxelseNothing)){-Note [maximumBy/minimumBy space usage]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~When the type signatures of maximumBy and minimumBy were generalized to workover any Foldable instance (instead of just lists), they were defined usingfoldr1. This was problematic for space usage, as the semantics of maximumByand minimumBy essentially require that they examine every element of thedata structure. Using foldr1 to examine every element results in space usageproportional to the size of the data structure. For the common case of lists,this could be particularly bad (see Trac #10830).For the common case of lists, switching the implementations of maximumBy andminimumBy to foldl1 solves the issue, as GHC's strictness analysis can thenmake these functions only use O(1) stack space. It is perhaps not the optimalway to fix this problem, as there are other conceivable data structures(besides lists) which might benefit from specialized implementations formaximumBy and minimumBy (seehttps://ghc.haskell.org/trac/ghc/ticket/10830#comment:26 for a furtherdiscussion). But using foldl1 is at least always better than using foldr1, soGHC has chosen to adopt that approach for now.-}

[8]ページ先頭

©2009-2025 Movatter.jp