Solved

Posted on 2009-12-19
658 Views
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
Question by:Fero45

LVL 24

Accepted Solution

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

LVL 6

Author Closing Comment

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

## Featured Post

### Suggested Solutions

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
This article will show, step by step, how to integrate R code into a R Sweave document
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.