PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 15, 2022

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

 December 15, 2022     haskell, syntax     No comments   

Issue

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?


Solution

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, ns, 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.



Answered By - Francis King
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing