dimanche 5 mai 2019

Problem with larg index when testing my code

I am trying to learn Haskell, I want to write a recursive function and do not use any library functions. The function nth ::Integer -> [a ] -> Maybe a takes an index n and a list of elements and returns the n-th element of the list (if the index is valid) or Nothing if the index is invalid.

My code:

nth :: Integer -> [a] -> Maybe a
nth a [] = Nothing
nth a (x:xs) |a == 1 = Just x 
             |fromIntegral (length xs) < a = Nothing 
             |a==0 = Nothing
             | otherwise = nth (a-1) xs  

I want to do this test to my code:

spec = do

    describe "nth" $ do
        it "for valid indexes it behaves like (!!)" $
            property $ \n xs -> n < 0 || (fromInteger n) >= length (xs::[Integer]) || Lists.nth n xs == Just (xs!!(fromInteger n))
        it "for negative indexes it returns Nothing" $
            property $ \n xs -> n >= 0 || Lists.nth n (xs::[Integer]) == Nothing
        it "for too large indexes it returns Nothing" $
            property $ \n xs -> (fromInteger n) < length xs || Lists.nth n (xs::[Integer]) == Nothing

but every time I am doing the test I'm getting an error

  for valid indexes it behaves like (!!) FAILED [1]
    for negative indexes it returns Nothing
      +++ OK, passed 100 tests.
    for too large indexes it returns Nothing FAILED [2]

1) Lists.nth for valid indexes it behaves like (!!)
       Falsified (after 5 tests and 5 shrinks):
         0
         [0]

  To rerun use: --match "/Lists/nth/for valid indexes it behaves like (!!)/"

  ./ListsSpec.hs:23:9: 
  2) Lists.nth for too large indexes it returns Nothing
       Falsified (after 38 tests):
         1
         [0]

Aucun commentaire:

Enregistrer un commentaire