ghc-lib-parser-9.12.2.20250421: The GHC API, decoupled from GHC versions

Safe Haskell | Ignore
Language | GHC2021

GHC.Utils.Misc

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

Description

Highly random utility functions

Synopsis

- applyWhen :: Bool -> (a -> a) -> a -> a
- nTimes :: Int -> (a -> a) -> a -> a
- const2 :: a -> b -> c -> a
- zipEqual :: HasDebugCallStack => String -> [a] -> [b] -> [(a, b)]
- zipWithEqual :: HasDebugCallStack => String -> (a -> b -> c) -> [a] -> [b] -> [c]
- zipWith3Equal :: HasDebugCallStack => String -> (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
- zipWith4Equal :: HasDebugCallStack => String -> (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
- stretchZipWith :: (a -> Bool) -> b -> (a -> b -> c) -> [a] -> [b] -> [c]
- zipWithAndUnzip :: (a -> b -> (c, d)) -> [a] -> [b] -> ([c], [d])
- zipAndUnzip :: [a] -> [b] -> ([a], [b])
- filterByList :: [Bool] -> [a] -> [a]
- filterByLists :: [Bool] -> [a] -> [a] -> [a]
- partitionByList :: [Bool] -> [a] -> ([a], [a])
- unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
- mapFst :: Functor f => (a -> c) -> f (a, b) -> f (c, b)
- mapSnd :: Functor f => (b -> c) -> f (a, b) -> f (a, c)
- chkAppend :: [a] -> [a] -> [a]
- mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
- mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
- mapAndUnzip4 :: (a -> (b, c, d, e)) -> [a] -> ([b], [c], [d], [e])
- filterOut :: (a -> Bool) -> [a] -> [a]
- partitionWith :: (a -> Either b c) -> [a] -> ([b], [c])
- partitionWithM :: Monad m => (a -> m (Either b c)) -> [a] -> m ([b], [c])
- dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
- spanEnd :: (a -> Bool) -> [a] -> ([a], [a])
- last2 :: [a] -> Maybe (a, a)
- lastMaybe :: [a] -> Maybe a
- onJust :: b -> Maybe a -> (a -> b) -> b
- foldl1' :: HasCallStack => (a -> a -> a) -> [a] -> a
- foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
- count :: (a -> Bool) -> [a] -> Int
- countWhile :: (a -> Bool) -> [a] -> Int
- all2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool
- any2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool
- lengthExceeds :: [a] -> Int -> Bool
- lengthIs :: [a] -> Int -> Bool
- lengthIsNot :: [a] -> Int -> Bool
- lengthAtLeast :: [a] -> Int -> Bool
- lengthAtMost :: [a] -> Int -> Bool
- lengthLessThan :: [a] -> Int -> Bool
- listLengthCmp :: [a] -> Int -> Ordering
- atLength :: ([a] -> b) -> b -> [a] -> Int -> b
- equalLength :: [a] -> [b] -> Bool
- compareLength :: [a] -> [b] -> Ordering
- leLength :: [a] -> [b] -> Bool
- ltLength :: [a] -> [b] -> Bool
- isSingleton :: [a] -> Bool
- only :: [a] -> a
- expectOnly :: HasDebugCallStack => String -> [a] -> a
- singleton :: a -> [a]
- notNull :: Foldable f => f a -> Bool
- expectNonEmpty :: HasDebugCallStack => String -> [a] -> NonEmpty a
- snocView :: [a] -> Maybe ([a], a)
- holes :: [a] -> [(a, [a])]
- changeLast :: [a] -> a -> [a]
- whenNonEmpty :: Applicative m => [a] -> (NonEmpty a -> m ()) -> m ()
- mergeListsBy :: (a -> a -> Ordering) -> [[a]] -> [a]
- isSortedBy :: (a -> a -> Ordering) -> [a] -> Bool
- mapMaybe' :: Foldable f => (a -> Maybe b) -> f a -> [b]
- fstOf3 :: (a, b, c) -> a
- sndOf3 :: (a, b, c) -> b
- thdOf3 :: (a, b, c) -> c
- fstOf4 :: (a, b, c, d) -> a
- sndOf4 :: (a, b, c, d) -> b
- fst3 :: (a -> d) -> (a, b, c) -> (d, b, c)
- snd3 :: (b -> d) -> (a, b, c) -> (a, d, c)
- third3 :: (c -> d) -> (a, b, c) -> (a, b, d)
- uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
- takeList :: [b] -> [a] -> [a]
- dropList :: [b] -> [a] -> [a]
- splitAtList :: [b] -> [a] -> ([a], [a])
- split :: Char -> String -> [String]
- dropTail :: Int -> [a] -> [a]
- capitalise :: String -> String
- sortWith :: Ord b => (a -> b) -> [a] -> [a]
- minWith :: Ord b => (a -> b) -> [a] -> a
- nubSort :: Ord a => [a] -> [a]
- ordNub :: Ord a => [a] -> [a]
- ordNubOn :: Ord b => (a -> b) -> [a] -> [a]
- isEqual :: Ordering -> Bool
- removeSpaces :: String -> String
- (<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
- (<||>) :: Applicative f => f Bool -> f Bool -> f Bool
- fuzzyMatch :: String -> [String] -> [String]
- fuzzyLookup :: String -> [(String, a)] -> [a]
- transitiveClosure :: (a -> [a]) -> (a -> a -> Bool) -> [a] -> [a]
- seqList :: [a] -> b -> b
- strictMap :: (a -> b) -> [a] -> [b]
- strictZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
- strictZipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
- looksLikeModuleName :: String -> Bool
- looksLikePackageName :: String -> Bool
- exactLog2 :: Integer -> Maybe Integer
- readRational :: String -> Rational
- readSignificandExponentPair :: String -> (Integer, Integer)
- readHexRational :: String -> Rational
- readHexSignificandExponentPair :: String -> (Integer, Integer)
- doesDirNameExist :: FilePath -> IO Bool
- getModificationUTCTime :: FilePath -> IO UTCTime
- modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)
- fileHashIfExists :: FilePath -> IO (Maybe Fingerprint)
- withAtomicRename :: MonadIO m => FilePath -> (FilePath -> m a) -> m a
- type Suffix = String
- splitLongestPrefix :: String -> (Char -> Bool) -> (String, String)
- escapeSpaces :: String -> String
- data Direction
  - = Forwards
  - | Backwards
- reslash :: Direction -> FilePath -> FilePath
- makeRelativeTo :: FilePath -> FilePath -> FilePath
- abstractConstr :: String -> Constr
- abstractDataType :: String -> DataType
- mkNoRepType :: String -> DataType
- charToC :: Word8 -> String
- hashString :: String -> Int32
- type HasCallStack = ?callStack :: CallStack
- type HasDebugCallStack = ()

# Miscellaneous higher-order functions

applyWhen :: Bool -> (a -> a) -> a -> a Source #

Apply a function iff some condition is met.

nTimes :: Int -> (a -> a) -> a -> a Source #

Apply a function `n` times to a given value.

const2 :: a -> b -> c -> a Source #

# General list processing

zipEqual :: HasDebugCallStack => String -> [a] -> [b] -> [(a, b)] Source #

zipWithEqual :: HasDebugCallStack => String -> (a -> b -> c) -> [a] -> [b] -> [c] Source #

zipWith3Equal :: HasDebugCallStack => String -> (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] Source #

zipWith4Equal :: HasDebugCallStack => String -> (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] Source #

stretchZipWith :: (a -> Bool) -> b -> (a -> b -> c) -> [a] -> [b] -> [c] Source #

`stretchZipWith p z f xs ys` stretches `ys` by inserting `z` in the places where `p` returns `True`

zipWithAndUnzip :: (a -> b -> (c, d)) -> [a] -> [b] -> ([c], [d]) Source #

zipAndUnzip :: [a] -> [b] -> ([a], [b]) Source #

This has the effect of making the two lists have equal length by dropping the tail of the longer one.

filterByList :: [Bool] -> [a] -> [a] Source #

`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 :: [Bool] -> [a] -> [a] -> [a] Source #

`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 :: [Bool] -> [a] -> ([a], [a]) Source #

`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.

unzipWith :: (a -> b -> c) -> [(a, b)] -> [c] Source #

mapFst :: Functor f => (a -> c) -> f (a, b) -> f (c, b) Source #

mapSnd :: Functor f => (b -> c) -> f (a, b) -> f (a, c) Source #

chkAppend :: [a] -> [a] -> [a] Source #

mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c]) Source #

mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d]) Source #

mapAndUnzip4 :: (a -> (b, c, d, e)) -> [a] -> ([b], [c], [d], [e]) Source #

filterOut :: (a -> Bool) -> [a] -> [a] Source #

Like filter, only it reverses the sense of the test

partitionWith :: (a -> Either b c) -> [a] -> ([b], [c]) Source #

Uses a function to determine which of two output lists an input element should join

partitionWithM :: Monad m => (a -> m (Either b c)) -> [a] -> m ([b], [c]) Source #

Monadic version of `partitionWith`

dropWhileEndLE :: (a -> Bool) -> [a] -> [a] Source #

spanEnd :: (a -> Bool) -> [a] -> ([a], [a]) Source #

`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).

last2 :: [a] -> Maybe (a, a) Source #

Get the last two elements in a list.

lastMaybe :: [a] -> Maybe a Source #

onJust :: b -> Maybe a -> (a -> b) -> b Source #

`onJust x m f` applies f to the value inside the Just or returns the default.

foldl1' :: HasCallStack => (a -> a -> a) -> [a] -> a Source #

A strict version of `foldl1`.

foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc Source #

count :: (a -> Bool) -> [a] -> Int Source #

countWhile :: (a -> Bool) -> [a] -> Int Source #

all2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool Source #

any2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool Source #

lengthExceeds :: [a] -> Int -> Bool Source #

    (lengthExceeds xs n) = (length xs > n)

lengthIs :: [a] -> Int -> Bool Source #

    (lengthIs xs n) = (length xs == n)

lengthIsNot :: [a] -> Int -> Bool Source #

    (lengthIsNot xs n) = (length xs /= n)

lengthAtLeast :: [a] -> Int -> Bool Source #

    (lengthAtLeast xs n) = (length xs >= n)

lengthAtMost :: [a] -> Int -> Bool Source #

    (lengthAtMost xs n) = (length xs <= n)

lengthLessThan :: [a] -> Int -> Bool Source #

    (lengthLessThan xs n) == (length xs < n)

listLengthCmp :: [a] -> Int -> Ordering Source #

atLength :: ([a] -> b) -> b -> [a] -> Int -> b Source #

`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)

equalLength :: [a] -> [b] -> Bool Source #

True if length xs == length ys

compareLength :: [a] -> [b] -> Ordering Source #

leLength :: [a] -> [b] -> Bool Source #

True if length xs <= length ys

ltLength :: [a] -> [b] -> Bool Source #

True if length xs < length ys

isSingleton :: [a] -> Bool Source #

only :: [a] -> a Source #

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.

expectOnly :: HasDebugCallStack => String -> [a] -> a Source #

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.

singleton :: a -> [a] Source #

notNull :: Foldable f => f a -> Bool Source #

expectNonEmpty :: HasDebugCallStack => String -> [a] -> NonEmpty a Source #

Like `expectJust msg . nonEmpty`; a better alternative to `fromList`.

snocView :: [a] -> Maybe ([a], a) Source #

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.

holes :: [a] -> [(a, [a])] Source #

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])]

changeLast :: [a] -> a -> [a] Source #

Replace the last element of a list with another element.

whenNonEmpty :: Applicative m => [a] -> (NonEmpty a -> m ()) -> m () Source #

mergeListsBy :: (a -> a -> Ordering) -> [[a]] -> [a] Source #

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) \)

isSortedBy :: (a -> a -> Ordering) -> [a] -> Bool Source #

mapMaybe' :: Foldable f => (a -> Maybe b) -> f a -> [b] Source #

# Tuples

fstOf3 :: (a, b, c) -> a Source #

sndOf3 :: (a, b, c) -> b Source #

thdOf3 :: (a, b, c) -> c Source #

fstOf4 :: (a, b, c, d) -> a Source #

sndOf4 :: (a, b, c, d) -> b Source #

fst3 :: (a -> d) -> (a, b, c) -> (d, b, c) Source #

snd3 :: (b -> d) -> (a, b, c) -> (a, d, c) Source #

third3 :: (c -> d) -> (a, b, c) -> (a, b, d) Source #

uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d Source #

# List operations controlled by another list

takeList :: [b] -> [a] -> [a] Source #

dropList :: [b] -> [a] -> [a] Source #

splitAtList :: [b] -> [a] -> ([a], [a]) Source #

Given two lists xs and ys, return `splitAt (length xs) ys`.

split :: Char -> String -> [String] Source #

dropTail :: Int -> [a] -> [a] Source #

drop from the end of a list

capitalise :: String -> String Source #

Convert a word to title case by capitalising the first letter

# Sorting

sortWith :: Ord b => (a -> b) -> [a] -> [a] Source #

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.

minWith :: Ord b => (a -> b) -> [a] -> a Source #

nubSort :: Ord a => [a] -> [a] Source #

ordNub :: Ord a => [a] -> [a] Source #

Remove duplicates but keep elements in order. O(n * log n)

ordNubOn :: Ord b => (a -> b) -> [a] -> [a] Source #

Remove duplicates but keep elements in order. O(n * log n)

# Comparisons

isEqual :: Ordering -> Bool Source #

removeSpaces :: String -> String Source #

(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool infixr 3 Source #

(<||>) :: Applicative f => f Bool -> f Bool -> f Bool infixr 2 Source #

# Edit distance

fuzzyMatch :: String -> [String] -> [String] Source #

fuzzyLookup :: String -> [(String, a)] -> [a] Source #

Search for possible matches to the users input in the given list, returning a small number of ranked results

# Transitive closures

transitiveClosure :: (a -> [a]) -> (a -> a -> Bool) -> [a] -> [a] Source #

# Strictness

seqList :: [a] -> b -> b Source #

strictMap :: (a -> b) -> [a] -> [b] Source #

strictZipWith :: (a -> b -> c) -> [a] -> [b] -> [c] Source #

strictZipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] Source #

# Module names

looksLikeModuleName :: String -> Bool Source #

looksLikePackageName :: String -> Bool Source #

# Integers

exactLog2 :: Integer -> Maybe Integer Source #

Determine the $log_2$ of exact powers of 2

# Floating point

readRational :: String -> Rational Source #

readSignificandExponentPair :: String -> (Integer, Integer) Source #

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)

readHexRational :: String -> Rational Source #

readHexSignificandExponentPair :: String -> (Integer, Integer) Source #

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

doesDirNameExist :: FilePath -> IO Bool Source #

getModificationUTCTime :: FilePath -> IO UTCTime Source #

modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime) Source #

fileHashIfExists :: FilePath -> IO (Maybe Fingerprint) Source #

withAtomicRename :: MonadIO m => FilePath -> (FilePath -> m a) -> m a Source #

# Filenames and paths

type Suffix = String Source #

splitLongestPrefix :: String -> (Char -> Bool) -> (String, String) Source #

escapeSpaces :: String -> String Source #

data Direction Source #

Constructors

Forwards |
Backwards |

reslash :: Direction -> FilePath -> FilePath Source #

makeRelativeTo :: FilePath -> FilePath -> FilePath Source #

# Utils for defining Data instances

abstractConstr :: String -> Constr Source #

abstractDataType :: String -> DataType Source #

mkNoRepType :: String -> DataType Source #

Constructs a non-representation for a non-representable type

# Utils for printing C code

charToC :: Word8 -> String Source #

# Hashing

hashString :: String -> Int32 Source #

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 = 0xdeadbeef

Where 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 = 100000

We discover that testp magic = 0.

# Call stacks

type HasCallStack = ?callStack :: CallStack Source #

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.

Since: base-4.9.0.0

type HasDebugCallStack = () Source #

A call stack constraint, but only when `isDebugOn`.