• Status: Solved
• Priority: Medium
• Security: Public
• Views: 814

Dear Experts

I understand that when I create my own myLength function, e.g.
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + myLength xs

and as example have a string "apple", the internal logic of Haskell is as follows:
1 + (myLength "pple")
1 + (1 + (myLength "ple"))
1 + (1 + (1 + (myLength "le")))
1 + (1 + (1 + (1 + (myLength "e"))))
1 + (1 + (1 + (1 + (1 + (myLength []])))))
1 + (1 + (1 + (1 + (1 + ( 0 )))))

We have the Haskell "drop" function (example taken from cs.arizona.edu)
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop _ [] = []
drop (n+1) (x:xs) = drop n xs

I do not understand the last line. Could somebody explain to me this function the same way as myLength using the same string "apple"?

Thanks
Fero
0
Fero45
1 Solution

Commented:
drop 0 xs = xs
is the end of the recursion

the line at the end does a recursive call but always with one lower than before.
let l = [ 1,2 ] let that be the list
drop 1 [1,2]

calls
drop 0 [2]  (see the pattern) (n+1) (x:xs)  so it "forgets the head of the list")

you than have
drop 0 [2]

and this yieds
[2]

Regards
Friedrich

0

Author Commented:
Thank you.
I got misled by addition  (n+1). I assumed it should be (n-1)
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.