I am trying to solve one of my Haskell question. The question asks me to that extracts a slice of a list of integers. Function should take a list and two indexes new list number contains between two indexes.
For this function;
- First index should smaller than second index
- First index cannot be negative number
- we cannot use any built-in functions
example:
makeSlice [1,2,3,4,5] 2 3
[3,4]
makeSlice [1,2,3,4,5] (-1) 3
*** Exception: First index cannot be negative
I tried a few option but below function if I give positive number I am getting "First index cannot be negative" exception
makeSlice :: [a] -> Int -> Int -> [a]
makeSlice [] _ _ =[]
makeSlice (h:t) i k
|k < 0 = []
| i>k = error "First index cannot be greater than second index (i > k)"
| i< 0 = error "First index cannot be negative (i < 0)!"
| i>0 = makeSlice t (i - 1) (k - 1)
| otherwise = h:makeSlice t (i -1 ) (k - 1)
Can you help me to find where I am making wrong?
otherwisecase, then you knowi< 0isFalseandi>0isFalse. Now think about what this implies about the value of(i -1 ). Is that what you intended? - Daniel WagnerFalsethen i > 0False? - macintoshi< 0andi>0before hitting theotherwisecase. So if you hit theotherwisecase, both of those must beFalse. - Daniel Wagneri > 0shouldi - 0otherwise should oni- macintosh