{-# LANGUAGE ScopedTypeVariables #-}moduleUtils.ListwhereimportData.ListimportData.FunctionimportData.MaybeimportControl.Arrow((&&&))importqualifiedData.MapasMimportTest.QuickCheck-- | Group list into indevidual pairs: [1,2,3,4] => [(1,2),(3,4)]. -- Works only with even number of elementspairs[]=[]pairs[x]=error"Non-even list for pair function"pairs(x:y:xs)=(x,y):pairsxs-- | Undo pairs functionfromPairs[]=[]fromPairs((x,y):xs)=x:y:fromPairsxsprop_pairsFromToxs=even(lengthxs)==>xs==fromPairs(pairsxs)-- | Group list into pairs: [1,2,3] => [(1,2),(2,3)]. -- Works with non null listspairs1x=zipx(tailx)-- | Undo pairs1 functionfromPairs1[]=[]fromPairs1[(x,y)]=[x,y]fromPairs1((x,y):xs)=x:fromPairs1(xs)prop_pairsFromTo1xs=lengthxs>1==>xs==fromPairs1(pairs1xs)creaseop=map(uncurryop).pairs1creaseMop=sequence.(creaseop)ranksfxs=mapfst$rankByfxsrankByfxs=map(\(rank,(orig,val))->(rank,val)).sortBy(compare`on`(fst.snd)).zip[1..].sortBy(f`on`snd).zip[1..]$xsclusterBy::Ordb=>(a->b)->[a]->[[a]]clusterByf=M.elems.M.mapreverse.M.fromListWith(++).map(f&&&return)groupItemsbaitems=map((b.head)&&&mapa).groupBy((==)`on`b).sortBy(comparingb)$items-- Assoc-list lookup with default valuelookupDefdalst=fromMaybed$lookupalst-- get all consecutive pairs of a list: --pairings "kissa"-- => [('k','i'),('i','s'),('s','s'),('s','a')]pairings[]=[]pairings[x,y]=[(x,y)]pairings(x:y:ys)=(x,y):pairings(y:ys)-- Perform an operation for each in lstforEachfunlst=unfoldrop([],lst)whereop(start,[])=Nothingop(start,a:as)=Just(start++(funa):as,(start++[a],as))forPairsfunlstlst2=map(mapfst)$forEach(\(a,b)->(funab,b))$ziplstlst2-- replicateListnl=concat$replicatenl--concatZipNub(a:as)(b:bs)|a==b=a:concatZipNubasbs|a/=b=a:b:concatZipNubasbsconcatZipNub[]_=[]concatZipNub_[]=[]histogrambinWidthvalues=(maplengrouped)wherelenx=(snap(headx),fromIntegral(lengthx))min=minimumvaluesmax=maximumvaluesgrouped=groupsortedsorted=sort$mapsnapvaluessnapx=binWidth*(fromIntegral$floor(x/binWidth))binListbinWidthopivs=zipbins(mapopvalues)wherevalues=map(mapsnd)groupedbins=map(fst.head)groupedgrouped=groupBy(\(a,_)(b,_)->a==b)sortedsorted=sortBy(comparingfst)$mapsnapIndexivssnapIndex(i,v)=(binWidth*(i`div`binWidth),v)-- Map numeric list so it becomes zeromeanzeroMeanlst=map(\x->x-mean)lstwheremean=averagelst-- Take n best elements according to fitnessestakeNAccordingTon(fitnesses,elements)=taken$sortBy(comparingfst)$zipfitnesseselements-- Zip two lists by selection functionselectc=zipWith(\ab->ifcabthenaelseb)-- Take halftakeHalflst=take(lengthlst`div`2)lstsplitToNPartsnlst|n<=0=error"splitToNParts n <= 0"|otherwise=takeLengths(lengths(lengthlst)n)lstwherelengthslenn=zipWith(+)(replicaten(len`div`n))(replicate(len`mod`n)1++repeat0)prop_splitEqnxs=n>0==>concat(splitToNPartsnxs)==xsprop_splitLennxs=n>0&&n<=(lengthxs)==>length(splitToNPartsnxs)==n-- Count elements that match predicate pcountp=foldl(\sumi->ifpithensum+1elsesum)0-- Count frequencies of elements in listfrequencieslst=map(\x->(headx,genericLengthx))$group$sortlstnormalizeFrequenciesls=map(\(a,b)->(a,b/sum(mapsndls)))ls-- Count average of listaverages=sums/(genericLength$s)-- Take n smallest given opsmallestByopnlst=smallestBy'opnlst[]smallestBy'opn[]o=osmallestBy'opn(i:input)[]=smallestBy'opninput[i]smallestBy'opn(i:input)output@(o:os)=smallestBy'opninput(taken$insertByopioutput)-- (sloppily) Count median of listmedians|oddlen=sorted!!middle|otherwise=((sorted!!middle)+(sorted!!(middle-1)))/2wheremiddle=len`div`2sorted=sortslen=lengthstakeTailnlst=reverse$taken$reverselst-- Count standard deviation of a list stdDevl=sqrt(sum(map(\x->(x-avg)^2)l)/genericLengthl)whereavg=averagel-- Transform a list so that nth element is sum of n first elementscumulate[]=[]cumulatevalues=tail$scanl(+)0valuesschwartzianTransform::(Orda,Ordb)=>(a->b)->[a]->[a]schwartzianTransformf=mapsnd.sort.map(\x->(fx,x))sortViaf=mapsnd.sortBycmp.map(\x->(fx,x))wherecmp(a1,a2)(b1,b2)=comparea1b1comparingpab=compare(pa)(pb)-- Pick element that has majority in the listmajoritylst=head$maximumBy(comparinglength)$group$sortlst-- Get all possible k-sized neighbourhoods in the listgetKNeighbourhoodskp=get(lengthp)pknotwherepknot=p++pknotget0p=[]getip=takekp:get(i-1)(tailp)prop_headIdentical_KNnxs=1<=n&&lengthxs>=1==>maphead(getKNeighbourhoodsnxs)==xs-- Split a list to `l` length pieces.splitToLengthllst=unfoldrsplitlstwheresplit[]=Nothingsplitlst=Just(takellst,dropllst)-- Take n pieces of given lengths--takeLengths :: [Int] -> [a] -> [[a]]takeLengths[]lst=[]takeLengths(l:ls)lst=takellst:takeLengthsls(dropllst)prop_takeLenlsxs=all(>=0)ls&&sumls<lengthxs==>length(takeLengthslsxs)==lengthlsprop_takeLenslsxs=all(>=0)ls&&sumls<lengthxs==>maplength(takeLengthslsxs)==ls-- From LicencedPreludeExts (hawiki)splitBy::(a->Bool)->[a]->[[a]]splitBy_[]=[]splitByflist=first:splitByf(dropWhilefrest)where(first,rest)=breakflist--splitBetween :: ((a,a) -> Bool) -> [a] -> [[a]]splitBetweencacc[]=[reverseacc]splitBetweencacc[a]=[reverse$a:acc]splitBetweencacc(a:b:cs)|cab=(reverse$a:acc):splitBetweenc[](b:cs)|otherwise=splitBetweenc(a:acc)(b:cs)-- split list into subsets matching predicatetearopl=(filter(not.op)l,filteropl)swapEverywhereab=concat$zipWithmerge(initsa)(tailsa)wheremergei[]=[]mergei(t:ts)=map(\x->i++[x]++ts)btakeWhile2oplst=reverse$twop[headlst](taillst)wheretw_l[]=[]twopl(x:xs)=ifop(headl)xthentwop(x:l)xselselapplyMapvalops=map(\op->opval)opsapplyMapM::(Monadm)=>a->[a->mb]->m[b]applyMapMvalops=mapM(\op->opval)opschangesM::(Monadm)=>[a->mb]->a->m[b]changesM=flipapplyMapMrollList(a:xs)=xs++[a]roll=rollListmergeListab=a++drop(lengtha)btakeWhile1test[]=[]takeWhile1test(x:xs)|testx=x:takeWhile1testxs|otherwise=[x]-- Modify each element in list with function that has knowledge of already-- modified elementseditingMapfl=editingTravf[]leditingTravfun[]l@(x:xs)=editingTravfun[(funlx)]xseditingTravfuna[]=reverseaeditingTravfunssl@(x:xs)=editingTravfun(fun(reversess++l)x:ss)xs-- Rotations of listrotate(x:xs)=xs++[x]cyclesx=take(lengthx)$iteraterotatex