scala - Findig the 2nd last item in the list, please explain this solution -
// pattern matching makes easy. def penultimaterecursive[a](ls: list[a]): = ls match { case h :: _ :: nil => h case _ :: tail => penultimaterecursive(tail) case _ => throw new nosuchelementexception }
can comment doing line line?
is [a] generic in c# ?
h doesn't seem defined?
i think major part of algo recursive call:
case _ :: tail => penultimaterecursive(tail)
there doesnt' seem check 2 items in list, , taking 1st item 2nd last, confused!
the keys understanding pattern match realize x :: y
only match list single item x
followed rest of list y
(which nil
, or many elements), , _
means "there needs here, won't bother naming it". (and matches occur in order, , lists end nil
.)
you're correct [a]
generic type.
so, first line:
case h :: _ :: nil => h
says, if our list looks (conceptually) node(h) -> node(whatever) -> nil
, return h
. two-element list first item selected. note nil
not match arbitrary tail of list; matches end-of-list item nil
. because of rule scala uses distinguish two: lower case variables treated wildcards have appropriate value filled in, while upper case variables treated constants match. (if must match lower-case name, can if surround backticks.)
okay, suppose it's not two-element list. if it's not empty, match
case _ :: tail => penultimaterecursive(tail)
so if haven't got two-element list, throw away first item , try again. finally, if somehow never ended two-element list, to
case _ => throw new nosuchelementexception
and we're done. (this case nil
, actually, since possibility doesn't match other 2 entries.)
Comments
Post a Comment