21

Could somebody clearly explain it with some good example. I came across this statement in Scala, when explaining about the functional programming.

Anil
  • 421
  • 1
  • 3
  • 11
  • 6
    I'm not sure if you mean this, but [first class functions](http://en.wikipedia.org/wiki/First-class_function)? – Mizuho May 27 '12 at 21:15
  • You may also look at [this](http://stackoverflow.com/a/1602050/298389) answer. It relates to general meaning rather that specifically scala one. – om-nom-nom May 27 '12 at 21:22
  • You might like to accept the answer that helped you the most. – Marcin May 29 '12 at 06:04
  • Does this answer your question? [What are "first-class" objects?](https://stackoverflow.com/questions/245192/what-are-first-class-objects) – Martin Mar 02 '23 at 14:44

6 Answers6

27

Being "first-class" is not a formally defined notion, but it generally means that an entity has three properties:

  1. It can be used, without restriction, wherever "ordinary" values can, i.e., passed and returned from functions, put in containers, etc.

  2. It can be constructed, without restriction, wherever "ordinary" values can, i.e., locally, in an expression, etc.

  3. It can be typed in a way similar to "ordinary" values, i.e., there is a type assigned to such an entity, and it can be freely composed with other types.

For functions, (2) particularly implies that a local function can use all names in scope, i.e. you have lexical closures. It also often comes with an anonymous form for construction (such as anonymous functions), but that is not strictly required (e.g. if the language has general enough let-expressions). Point (3) is trivially true in untyped languages.

So you see why functions in Scala (and in functional languages) are called first-class. Here are some other examples.

  • Functions in C/C++ are not first-class. While (1) and (3) are arguably available through function pointers, (2) is not supported for functions proper. (A point that's often overlooked.)

  • Likewise, arrays and structs are not first-class in C land.

  • Classes in Scala are not first-class. You can define and nest them, but not e.g. pass them to a function (only its instances). There are OO-languages with first-class classes, and in fact, the so-called nuObj calculus that informed Scala's design also allows that.

  • First-class modules are an often desired feature in ML-like languages. They are difficult, because they lead to undecidable type-checking. Some ML dialect allow modules to be wrapped up as first-class values, but arguably, that does not make modules first-class themselves.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72
  • 1
    Similarly, from [Learning Scala](https://www.safaribooksonline.com/library/view/learning-scala/9781449368814/ch05.html), functions are first-class because you can: (1) create without giving a name, (2) put into arrays and other structures, and (3) be used as a parameter or return value – Josiah Yoder Jul 13 '16 at 18:32
  • I'm not sure that lexical closures are a necessary implication. Many Lisp dialects don't have lexical closures (MacLisp had downward funargs, but not upwards), but functions were still considered to be first-class objects. – Barmar Apr 15 '22 at 15:07
15

It means that functions can be passed around the same way as integers, sequences, etc.

An example (although not Scala):

>>> def add2(x):
...   return x + 2
... 
>>> map(add2, [1, 2, 3])
[3, 4, 5]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
9

Any programming language has a basic set of language features that you can use to manipulate values, in order to write programs. These are things like: "pass a value to a function", "bind a variable to a value, and then use the variable as if it were the value", etc.

Whenever you see that a claim that a language has "X as first class values", or has "first class Xs", this means that the language allows you to use those basic language features on Xs. Another way to say that is that the language treats Xs as values.

So you can fill in the blank to say that some language has support for using some particular kind of thing as values. For example, Scala has first class functions (or functions are values in Scala):

def plusOne(x : Int) = x + 1
val func : Int => Int = plusOne
println(func(1))     // prints 2

Python has first-class functions, but also has first-class classes (classes are values in Python):

class Foo(object):
    def __init__(self, thing):
        self.thing = thing

cls = Foo
instance = cls(5)
print instance.thing            # prints 5
print isinstance(thing, cls)    # prints True
print isinstance(thing, Foo)    # prints True

This might not seem like much, but the basic features of any programming language saying what you can do with values lead to the more stuff; if you can use functions as values, then (like any other value) you can put them in containers, retrieve unknown ones by invoking other code, etc, etc.

In contrast, Java does not have first-class functions. You can't put a function in a variable, pass one to another function, or receive one as the return value of a function. Functions are not values in Java. Neither does Java have first-class classes.

Ben
  • 68,572
  • 20
  • 126
  • 174
  • Special thanks to your Python first-class classes example. By the way, could you shed some light on this question [What decides if function or class can be first class values for a programming language?](https://stackoverflow.com/questions/71885644/what-decides-if-function-or-class-can-be-first-class-values-for-a-programming-la) ? I can't find much material by Googling – Rick Apr 15 '22 at 15:03
3

It means that a function is an object. And just like any other object it can be assigned to a variable, or passed to a function, or anything else that objects can do.

For example, here is a variable f that holds a function object that adds 1 to an integer:

scala> val f = (n: Int) => n + 1
f: Int => Int = <function1>       // Has type Int => Int; Int input, Int output

It can be passed as an argument to the map function of a List[Int]:

scala> List(1,2,3).map(f)         // map requires argument of type Int => Int
res0: List[Int] = List(2, 3, 4)
dhg
  • 52,383
  • 8
  • 123
  • 144
  • 6
    While its accurate to say that the function is an object in Scala, that is not generally true in functional languages; especially those that are not object oriented. – BillRobertson42 May 27 '12 at 21:16
  • Thank you so much for the good example. I understood the concept behind it. I have a doubt with the first two lines of code. I will be grateful if you make it more clear to me. – Anil May 27 '12 at 21:34
  • They syntax of the first bit just means that I'm declaring a variable `f` and assigning it to be a function literal. The `=>` operator constructs a function where the left side is the inputs and the right side is the body. So it accepts an `Int` called `n` and it adds one to it. The line below it is just the type that is seen when you run that line in the Scala REPL. – dhg May 27 '12 at 21:39
  • It might be more clear if instead of `f` you give it a name like `addOne`. – Chuck May 27 '12 at 21:41
  • I got it now. Thank you so much for being more clear. I got confused with the REPL.Now its fine. – Anil May 27 '12 at 21:45
2

It's a term taken from purely functional languages such as Haskell or Erlang where functions are first class citizens. It means that functions can be passed as arguments to other functions and functions can return other functions.

Because functions are first class citizens – we have a function type – signified by an arrow. In haskel: (->) In skala: (=>)

Consider map function. It's a function which takes a function and a list as its arguments and applies given function to all the elements of the list:

in haskell:

map(\x->x+1)[1,2,3] 
= [2,3,4]

in scala:

List(1,2,3) map (x => x + 1) 
= [2,3,4]

(\x->x+1) and (x => x + 1) are functions (denoted by lambda expressions) passed to map function as arguments.

Mark
  • 821
  • 7
  • 14
0

In functional programming, functions can be assigned to variables, passed to other functions as parameters, and returned as values from other functions. Such functions are known as First Class Functions. A higher-order function is a function which takes a function as argument or returns a function.

Example:

var increase = (x: Int) => x + 1
clemens
  • 16,716
  • 11
  • 50
  • 65