Apply a function iff some condition is met.
Moduleghc-lib-parser-9.14.1.20251220GHC2021
GHC.Utils.Misc
Highly random utility functions
Contents
- Miscellaneous higher-order functions
- General list processing
- Tuples
- List operations controlled by another list
- Sorting
- Comparisons
- Edit distance
- Transitive closures
- Strictness
- Module names
- Integers
- Floating point
- IO-ish utilities
- Filenames and paths
- Utils for defining Data instances
- Utils for printing C code
- Hashing
- Call stacks
Synopsis
- value applyWhen
- value nTimes
- value const2
- value zipEqual
- value zipWithEqual
- value zipWith3Equal
- value zipWith4Equal
- value stretchZipWith
- value zipWithAndUnzip
- value zipAndUnzip
- value filterByList
- value filterByLists
- value partitionByList
- value unzipWith
- value mapFst
- value mapSnd
- value chkAppend
- value mapAndUnzip
- value mapAndUnzip3
- value mapAndUnzip4
- value filterOut
- value partitionWith
- value partitionWithM
- value dropWhileEndLE
- value spanEnd
- value last2
- value lastMaybe
- value onJust
- value foldl2
- value count
- value countWhile
- value all2
- value any2
- value all2Prefix
- value all3Prefix
- value foldr1WithDefault
- value foldl1WithDefault'
- value lengthExceeds
- value lengthIs
- value lengthIsNot
- value lengthAtLeast
- value lengthAtMost
- value lengthLessThan
- value listLengthCmp
- value atLength
- value equalLength
- value compareLength
- value leLength
- value ltLength
- value isSingleton
- value only
- value expectOnly
- value singleton
- value notNull
- value expectNonEmpty
- value snocView
- value holes
- value changeLast
- value whenNonEmpty
- value mergeListsBy
- value isSortedBy
- value mapMaybe'
- value fstOf3
- value sndOf3
- value thdOf3
- value fstOf4
- value sndOf4
- value fst3
- value snd3
- value third3
- value uncurry3
- value takeList
- value dropList
- value splitAtList
- value split
- value dropTail
- value capitalise
- value sortWith
- value minWith
- value nubSort
- value ordNub
- value ordNubOn
- value isEqual
- value removeSpaces
- value <&&>
- value <||>
- value fuzzyMatch
- value fuzzyLookup
- value transitiveClosure
- value seqList
- value strictMap
- value strictZipWith
- value strictZipWith3
- value looksLikeModuleName
- value looksLikePackageName
- value exactLog2
- value readRational
- value readSignificandExponentPair
- value readHexRational
- value readHexSignificandExponentPair
- value doesDirNameExist
- value getModificationUTCTime
- value modificationTimeIfExists
- value fileHashIfExists
- value withAtomicRename
- type Suffix
- value splitLongestPrefix
- value escapeSpaces
- data Direction
- value reslash
- value makeRelativeTo
- value abstractConstr
- value abstractDataType
- value mkNoRepType
- value charToC
- value hashString
- type HasCallStack
- type HasDebugCallStack
- Packageghc-lib-parser-9.14.1.20251220
- Exports118
- LanguageGHC2021
- LicenceBSD-3-Clause
- SourceMisc.hs
Miscellaneous higher-order functions
Apply a function n times to a given value.
General list processing
stretchZipWith p z f xs ys stretches ys by inserting z in
the places where p returns True
This has the effect of making the two lists have equal length by dropping the tail of the longer one.
filterByList takes a list of Bools and a list of some elements and filters out these elements for which the corresponding value in the list of Bools is False. This function does not check whether the lists have equal length.
filterByLists takes a list of Bools and two lists as input, and outputs a new list consisting of elements from the last two input lists. For each Bool in the list, if it is True, then it takes an element from the former list. If it is False, it takes an element from the latter list. The elements taken correspond to the index of the Bool in its list. For example:
filterByLists [True, False, True, False] "abcd" "wxyz" = "axcz"
This function does not check whether the lists have equal length.
partitionByList takes a list of Bools and a list of some elements and
partitions the list according to the list of Bools. Elements corresponding
to True go to the left; elements corresponding to False go to the right.
For example, partitionByList [True, False, True] [1,2,3] == ([1,3], [2])
This function does not check whether the lists have equal
length; when one list runs out, the function stops.
Like filter, only it reverses the sense of the test
Uses a function to determine which of two output lists an input element should join
Monadic version of partitionWith
spanEnd p l == reverse (span p (reverse l)). The first list
returns actually comes after the second list (when you look at the
input list).
Get the last two elements in a list.
onJust x m f applies f to the value inside the Just or returns the default.
`all2Prefix p xs ys` is a fused version of `and $ zipWith2 p xs ys`.
(It generates good code nonetheless.)
So if one list is shorter than the other, p is assumed to be True for the
suffix.
`all3Prefix p xs ys zs` is a fused version of `and $ zipWith3 p xs ys zs`.
(It generates good code nonetheless.)
So if one list is shorter than the others, p is assumed to be True for
the suffix.
(lengthExceeds xs n) = (length xs > n)(lengthIs xs n) = (length xs == n)(lengthIsNot xs n) = (length xs /= n)(lengthAtLeast xs n) = (length xs >= n)(lengthAtMost xs n) = (length xs <= n)(lengthLessThan xs n) == (length xs < n)atLength atLen atEnd ls n unravels list ls to position n. Precisely:
atLength atLenPred atEndPred ls n
| n < 0 = atLenPred ls
| length ls < n = atEndPred (n - length ls)
| otherwise = atLenPred (drop n ls)
True if length xs == length ys
True if length xs <= length ys
True if length xs < length ys
Utility function to go from a singleton list to it's element.
Wether or not the argument is a singleton list is only checked in debug builds.
Extract the single element of a list and panic with the given message if
there are more elements or the list was empty.
Like expectJust, but for lists.
Like expectJust msg . nonEmpty; a better alternative to NE.fromList.
Split a list into its last element and the initial part of the list.
snocView xs = Just (init xs, last xs) for non-empty lists.
snocView xs = Nothing otherwise.
Unless both parts of the result are guaranteed to be used
prefer separate calls to last + init.
If you are guaranteed to use both, this will
be more efficient.
Compute all the ways of removing a single element from a list.
holes [1,2,3] = [(1, [2,3]), (2, [1,3]), (3, [1,2])]Replace the last element of a list with another element.
Merge an unsorted list of sorted lists, for example:
mergeListsBy compare [ [2,5,15], [1,10,100] ] = [1,2,5,10,15,100] O(n \log{} k)
Tuples
List operations controlled by another list
Given two lists xs and ys, return `splitAt (length xs) ys`.
drop from the end of a list
Convert a word to title case by capitalising the first letter
Sorting
The sortWith function sorts a list of elements using the user supplied function to project something out of each element
In general if the user supplied function is expensive to compute then you should probably be using sortOn, as it only needs to compute it once for each element. sortWith, on the other hand must compute the mapping function for every comparison that it performs.
Remove duplicates but keep elements in order. O(n * log n)
Remove duplicates but keep elements in order. O(n * log n)
Comparisons
Edit distance
Search for possible matches to the users input in the given list, returning a small number of ranked results
Transitive closures
Strictness
Module names
Integers
Determine the $log_2$ of exact powers of 2
Floating point
Parse a string into a significand and exponent. A trivial example might be: ghci> readSignificandExponentPair "1E2" (1,2) In a more complex case we might return a exponent different than that which the user wrote. This is needed in order to use a Integer significand. ghci> readSignificandExponentPair "-1.11E5" (-111,3)
Parse a string into a significand and exponent according to the "Hexadecimal Floats in Haskell" proposal. A trivial example might be: ghci> readHexSignificandExponentPair "0x1p+1" (1,1) Behaves similar to readSignificandExponentPair but the base is 16 and numbers are given in hexadecimal: ghci> readHexSignificandExponentPair "0xAp-4" (10,-4) ghci> readHexSignificandExponentPair "0x1.2p3" (18,-1)
IO-ish utilities
Filenames and paths
Utils for defining Data instances
Constructs a non-representation for a non-representable type
Utils for printing C code
Hashing
A sample hash function for Strings. We keep multiplying by the golden ratio and adding. The implementation is:
hashString = foldl' f golden
where f m c = fromIntegral (ord c) * magic + hashInt32 m
magic = 0xdeadbeefWhere hashInt32 works just as hashInt shown above.
Knuth argues that repeated multiplication by the golden ratio will minimize gaps in the hash space, and thus it's a good choice for combining together multiple keys to form one.
Here we know that individual characters c are often small, and this produces frequent collisions if we use ord c alone. A particular problem are the shorter low ASCII and ISO-8859-1 character strings. We pre-multiply by a magic twiddle factor to obtain a good distribution. In fact, given the following test:
testp :: Int32 -> Int
testp k = (n - ) . length . group . sort . map hs . take n $ ls
where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']]
hs = foldl' f golden
f m c = fromIntegral (ord c) * k + hashInt32 m
n = 100000We discover that testp magic = 0.
Call stacks
Request a CallStack.
NOTE: The implicit parameter ?callStack :: CallStack is an
implementation detail and should not be considered part of the
CallStack API, we may decide to change the implementation in the
future.
A call stack constraint, but only when isDebugOn.