implemented nth

This commit is contained in:
Jonathan Lamothe 2019-09-18 02:16:10 -04:00
parent ed9e437a1a
commit 3d705c4e6d
3 changed files with 75 additions and 0 deletions

29
src/Mtlstats/Util.hs Normal file
View File

@ -0,0 +1,29 @@
{- |
mtlstats
Copyright (C) 2019 Rhéal Lamothe
<rheal.lamothe@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
module Mtlstats.Util (nth) where
nth :: Int -> [a] -> Maybe a
nth _ [] = Nothing
nth n (x:xs)
| n == 0 = Just x
| n < 0 = Nothing
| otherwise = nth (pred n) xs

View File

@ -26,6 +26,7 @@ import qualified FormatSpec as Format
import qualified HandlersSpec as Handlers import qualified HandlersSpec as Handlers
import qualified ReportSpec as Report import qualified ReportSpec as Report
import qualified TypesSpec as Types import qualified TypesSpec as Types
import qualified UtilSpec as Util
main :: IO () main :: IO ()
main = hspec $ do main = hspec $ do
@ -34,3 +35,4 @@ main = hspec $ do
Format.spec Format.spec
Handlers.spec Handlers.spec
Report.spec Report.spec
Util.spec

44
test/UtilSpec.hs Normal file
View File

@ -0,0 +1,44 @@
{-
mtlstats
Copyright (C) 2019 Rhéal Lamothe
<rheal.lamothe@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
module UtilSpec (spec) where
import Test.Hspec (Spec, context, describe, it, shouldBe)
import Mtlstats.Util
spec :: Spec
spec = describe "Mtlstats.Util"
nthSpec
nthSpec :: Spec
nthSpec = describe "nth" $ mapM_
(\(n, expected) -> context (show n) $
it ("should be " ++ show expected) $ let
xs = ["foo", "bar", "baz"]
in nth n xs `shouldBe` expected)
-- index, expected
[ ( 0, Just "foo" )
, ( 1, Just "bar" )
, ( 2, Just "baz" )
, ( 3, Nothing )
, ( -1, Nothing )
]