Haskell - span elem: evaluation

I would like to know how haskell evauates the following expression.

span (`elem` ['A'..'Z']) "BOBsidneyMORGANeddy"

      

Result

("BOB","sidneyMORGANeddy")

      

Can anyone explain the assessment process to me? Because I cannot tell why it is split like above.

+3


source to share


1 answer


span

splits the list in two using a predicate such that the first part is the longest prefix for which the given predicate evaluates to true, and the second part is the rest of the list. In other words, the first part is obtained as c takeWhile

, and the second part is obtained as c dropWhile

for the same predicate.

Now let's look at the predicate. elem :: a->[a]->Bool

indicates whether the given item is found in the given list. The best trick is that any function of two or more arguments can be used in infix notation:

x `elem` xs

      

matches elem x xs

. Hence,



`elem` xs

      

handled exactly the same as infix function sections. This is the same as \x -> elem x xs

.

Now you can see what the span

predicate gets to see if the list items to split can be found in the list ['A'..'Z']

. Thus, it will split the list in two: it will find the first element for which the predicate fails and that is the split point. This is how the second section begins with the first lowercase letter.

+6


source







All Articles