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

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

-- | Find the @k@th element of a list.
-- The first element in the list is number 1.
elementAt :: [a] -> Int -> Maybe a
elementAt :: forall a. [a] -> Int -> Maybe a
elementAt [] Int
_ = Maybe a
forall a. Maybe a
Nothing
elementAt (a
x:[a]
xs) Int
k
  | Int
k Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1    = a -> Maybe a
forall a. a -> Maybe a
Just a
x
  | Int
k Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1     = [a] -> Int -> Maybe a
forall a. [a] -> Int -> Maybe a
elementAt [a]
xs (Int
kInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)
  | Bool
otherwise = Maybe a
forall a. Maybe a
Nothing