24

I found this code snipped on the internet:

digits 0 = [0]
digits n = digits' n []
  where digits' 0 ds = ds
        digits' n ds = let (q,r) = quotRem n 10
                       in digits' q (r:ds)

sumOfDigits = sum . digits

Can someone quickly explain what the " ' " sign ( digits n = digits' n [] ) after the recursive function call is for? I've seen some other code examples in Haskell (tutorials), but im not understandig this one. A quick explanation is appreciated.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
kiltek
  • 3,183
  • 6
  • 47
  • 70
  • I personally try to avoid using apostrophes in my identifiers because I'm too big a fan of Descriptive And Meaningful Phrases. – jcarpenter2 Jan 23 '14 at 23:59

2 Answers2

42

The apostrophe is just part of the name. It is a naming convention (idiom) adopted in Haskell.

The convention in Haskell is that, like in math, the apostrophe on a variable name represents a variable that is somehow related, or similar, to a prior variable.

An example:

let x  = 1
    x' = x * 2
in x'

x' is related to x, and we indicate that with the apostrophe.


You can run this in GHCi, by the way,

Prelude> :{ 
Prelude| let x  = 1
Prelude|     x' = x * 2
Prelude| in x'
Prelude| :}
2
Don Stewart
  • 137,316
  • 36
  • 365
  • 468
  • Your example doesn't work. Neither in a .hs file nor directly written into the Interpreter. – kiltek Apr 15 '11 at 08:16
  • @user504060: Try `let { x = 1; x' = x * 2 } in x'`. (Multiline constructs don't work as is in ghci, and expressions don't go at the top level of a Haskell source file.) – dave4420 Apr 15 '11 at 08:21
  • 1
    It's a Haskell expression. I've edited the answer to show how you can evaluate multiline expressions in GHCi. – Don Stewart Apr 15 '11 at 08:23
  • 4
    +1 for showing how to use layout in ghci. I didn't know that. – John L Apr 15 '11 at 08:55
10

It's just another character allowed in identifiers. Think of it as another letter.

augustss
  • 22,884
  • 5
  • 56
  • 93