{- |
Description: Insert element into a list
Copyright: Copyright (C) 2021 Yoo Chung
License: GPL-3.0-or-later
Maintainer: dev@chungyc.org

Some solutions to "Problems.P21" of Ninety-Nine Haskell "Problems".
-}
module Solutions.P21 (insertAt) where

-- | Insert an element at a given position into a list.
insertAt :: a -> [a] -> Int -> [a]
insertAt :: forall a. a -> [a] -> Int -> [a]
insertAt a
x [a]
xs Int
n = [a]
front [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a
x] [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a]
back
  where front :: [a]
front = Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) [a]
xs
        back :: [a]
back = Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
drop (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) [a]
xs