{-# LANGUAGE NoImplicitPrelude #-}
module Imj.Util
(
showListOrSingleton
, replicateElements
, range
, commonPrefix
, commonSuffix
, randomRsIO
, clamp
, Int64
) where
import Imj.Prelude
import Data.Int(Int64)
import Data.List(reverse)
import Data.Text(Text, pack)
import Control.Arrow( first )
import System.Random( Random(..)
, getStdRandom
, split )
{-# INLINABLE showListOrSingleton #-}
showListOrSingleton :: Show a => [a] -> Text
showListOrSingleton [e] = pack $ show e
showListOrSingleton l = pack $ show l
{-# INLINE replicateElements #-}
replicateElements :: Int -> [a] -> [a]
replicateElements n = concatMap (replicate n)
{-# INLINABLE range #-}
range :: Enum a => Ord a
=> a
-> a
-> [a]
range n m =
if m < n
then
[n,(pred n)..m]
else
[n..m]
randomRsIO :: Random a
=> a
-> a
-> IO [a]
randomRsIO from to =
getStdRandom $ split >>> first (randomRs (from, to))
commonPrefix :: String -> String -> String
commonPrefix (x:xs) (y:ys)
| x == y = x : commonPrefix xs ys
commonPrefix _ _ = []
commonSuffix :: String -> String -> String
commonSuffix s s' = reverse $ commonPrefix (reverse s) (reverse s')
{-# INLINABLE clamp #-}
clamp :: Ord a
=> a
-> a
-> a
-> a
clamp n min_ max_
| n < min_ = min_
| n > max_ = max_
| otherwise = n