简体   繁体   中英

What is the meaning of (n:ns) in Haskell?

In the first chapter of the book, Programming in Haskell, it has the following function definition:

summ [] = 0
summ (n:ns) = n + summ ns

What is the meaning of (n:ns) , I guess from the function ns is a list and n is the first element of the original list, but what does the (n:ns) notation actually tell Haskell? What part of the notation makes it clear what happens in the function?

The sequence (n:ns) is a shorthand for head - tail. Quite literally, the first value, the head, is called n and the remained are the other, potentially plural, n s, which is why it is called ns .

Haskell has pattern matching. So, if I say (n:ns) = [1,2,3] then Haskell will pattern match n to 1 , and ns to match [2,3] . Effectively, n:ns salami slices the first value off the front of the list.

The algorithm for calculating the sum of a list in Haskell is recursive. If the list is empty, [ ] , then zero is returned. Otherwise, we slice off the first value from the list, n , and add it to the result.

Haskell has a REPL, called ghci, and using this is fundamental to getting the hang of the language.

: builds lists.

Prelude> :t (:)
(:) :: a -> [a] -> [a]

It takes an element of type a , and a list of the same type elements. That list may be either empty ( [] ) or some element on the front of some other list. The definition of lists this way allows for lists of any number of elements.

[1, 2, 3, 4] is just a nice shorthand for 1 : 2 : 3 : 4 : [] .

The same syntax is used for destructuring lists. The pattern n:ns binds n to the head and ns to the tail of a list. Nothing stops you from using the pattern n:n':ns to bind n to the first element, n' to the second element, and ns to the rest .

Consider the usefulness of this in finding a list of every other element of a list. The _ pattern is used for a portion of the pattern we don't actually need to name.

everyOther :: [a] -> [a]
everyOther []       = []
everyOther (n:[])   = [n]
everyOther (n:_:ns) = n : everyOther ns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM