百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

关于函数的一些思考(关于函数的结论)

toyiye 2024-08-10 21:42 15 浏览 0 评论

什么是函数?

In imperative programming, we often say a function is a sub-module of out program. In order to make our program readable and clean, we often make the repeated parts into functions, then call then in the main part of program with parameters.

For example,

int foo(int a) {
    return a + 5;
}

If we have arbitrary integer $a$ and want to apply the `+ 5` arithmetic on `a`,

we can just use `foo(a)`.

Deep behind this is a "subroutine", another piece of code somewhere in memory that will do something to some value on stack, which is actually divergent from the definition of real "function". For example,

foo:
    pushq   %rbp	
    movq    %rsp, %rbp
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %eax
    addl    $5, %eax	; here it does the job
    popq    %rbp

main: ; something

But how do we interpret the concept of function in math?

函数的定义

As we know from math class, function is a mapping between two sets of objects (any objects!). Suppose $X$ and $Y$ are sets. If $f$ is a function from $X$ to $Y$, we write $ f : X \rightarrow Y $ and denote the element of $Y$ assigned to an element $x \in X$ by $f(x)$.

In Haskell, we can define a function very similar to this. Let `X` and `Y` be sets (types), a function mapping `X` to `Y` is

f :: X -> Y

and a function application of `x` in `X` is `f x` (without parenthesis).

From here you can see Haskell is trying it best to make the syntax as close to math as possible. `:` is defined as an operator in Haskell, so we use `::` in the function definition.

Note

  • `f :: X -> Y` is also called a type signature of a function.
  • Function is *left-associative*,

so we can ignore the parenthesis when function application, as what Haskell did in its syntax. That is, $fx$ is equivalent to $f(x)$.

常见的函数

As it is defined, function can map anything to anything! Let's see some typical functions.

啥也不干的函数

In mathematics, there is a function that does literally nothing.

Definition .

An identity function maps anything to itself.

That is, for all $x \in A$, function $\mathbb{1} : A \rightarrow A$ is defined as

$ \mathbb{1}(x) = \mathbb{1}x = x. $

(The first step is a demonstration of the left-associativity).

In Haskell, we have the predefined identity function for generic type `a`:

id :: a -> a

With the identity function, we can actually define a functional "variable",

x = id 5 :: Int

-- same as
x = 5

Why functional "variable"? In a pure functional language such as Haskell,there is no real variable for the purpose of eliminating side effects.

That is, all data is immutable . Many modern languages/tools also have this property,

for example, [React](https://flaviocopes.com/react-immutability/) and [Redux](https://redux.js.org/faq/immutable-data).

Fun Knowledge:

in math, we often ose the fancy 1, $\mathbb{1}$ or in $\LaTeX$ `\mathbb{1}`, to denote the identity.

Why?

There is a saying that if we define multiplication on the real numbers $\mathbb{R}$,

then 1 is the identity element such that $\forall x \in \mathbb{R} \setminus \\{0\\}$,

$ 1 \times x = x \times 1 = x. $

作用在数上的函数

This is the most common type of function we learned in math. These functions accompany us from middle all the way to college (or even grad school if you focus on analysis.)

These function can be categorized into two major classification:

  • functions defined on $\mathbb{R}$, $ f : \mathbb{R} \rightarrow \mathbb{R} $
  • and those are not, $ f : \mathbb{C} \rightarrow \mathbb{C}. $

(Real Analysis and Complex Analysis are the math course that study the behavior of these functions.)

As for programming, we mostly focus on functions defined on $\mathbb{R}$.

The first imperative example, if we define it as a function, it also falls in this type.

foo :: Int -> Int
foo x = x + 5

These functions can have many interesting property with respect to the set they are acting on.

For example, there are different type of sets.There are open and closed set, compact, or connected sets, each having some special structures.A continuous function on a set preserves the structure of that set.

That is, let $f : A \rightarrow \mathbb{R}$ be continuous on $A$. If $K \subseteq A$ is compact (or connected, or have other structures), then the set $fK$ is also compact (or connected, or have other structures).

If you are interested in this topic, go find some resources on Real Analysis and basic Topology. Also, I may write blog posts about this in the future.

A permutation is also this kind of function,

which is a bijection defined on a set of $n$ distinct elements $S$,

$ p : S \rightarrow S. $

For more information of permutation, see [Permualgebra](/2020/12/20/PermuAlgebra/index.html).

Binary Operations (Composition)

A binary operation on a set $S$ is a function

$ * : S \times S \rightarrow S $

its mapping is $(a,b) \mapsto a * b$.

Here the $\times$ operator is the **Cartesian product**, where

$ X \times Y = \\{ (x,y): x \in X, y \in Y \\}. $

In other words, a binary operations is just some function that takes two inputs and returns one output. For example, addition, multiplication, function composition, are all binary operations.

Discussion: Is division a binary operation?

There is another notation system for functions with more than 1 parameters in math, called [Currying](https://en.wikipedia.org/wiki/Currying),

$ * : S \rightarrow S \rightarrow S, $

where we see the last set as the output set(type), and the all the sets(types) before it as the input sets(types).

As we define in algebra, addition is

$ + : \mathbb{Z} \times \mathbb{Z} \rightarrow \mathbb{Z}, $

which can also be express as

$ + : \mathbb{Z} \rightarrow \mathbb{Z} \rightarrow \mathbb{Z}. $

There is a little difference between this two notation, we will discuss the details in post [Introduction to Lambda Calculus].

In haskell, we can define function in the currying way,

(+) :: Integer -> Integer -> Integer

Note: type `Integer` in Haskell is an arbitrary precision type which will hold any number no matter how big, type `Int` is the standard `int` type in computer science.

By the way, Cartesian product itself is a binary operator. Write the definition of Cartesian product in Currying notation, $ \times : X \rightarrow Y \rightarrow (X,Y) $ where

$ X \times Y = \\{ (x,y): x \in X, y \in Y \\}. $

we can define it very easily using Haskell list comprehensions .

cartesian :: [a] -> [b] -> [(a,b)]
cartesian xs ys = [(x, y) | x <- xs, y <- ys]

Haskell also support infix operator definition automatically, for example

Prelude> cartesian [1..3] [1..3]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
Prelude> [1..3] `cartesian` [1..3]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

You can also define the function the infix way

cartesian :: [a] -> [b] -> [(a,b)]

xs `cartesian` ys = [(x, y) | x <- xs, y <- ys]

which is equivalent to the first definition.

If we relate the math symbol with Haskell syntax, where

$\\{\\} \leftrightarrows$ `[]`,

$:\,\leftrightarrows$ `|`,

$\in\,\leftrightarrows$ `<-`,

then math definition and Haskell code looks exactly the same!

Definition:

An identity for a binary operation on set $S$ is an unique element $e \in S$ such that

$ ae = a = ea $ for all $a \in S $.

We often use $\mathbb{1}$ to denote the identity.

Isn't this definition familiar?

Binary Operation on List

There are two major binary operator of lists.Since there are no lists in real math, I will just write the Haskell type signature.

`:` is the operator that joint a element and a list of the same type, and `++` joints two lists of same type.

(:) :: a -> [a] -> [a]
(++) :: [a] -> [a] -> [a]
Prelude> 1 : [2..10]
[1,2,3,4,5,6,7,8,9,10]
Prelude> [1..5] ++ [6..10]
[1,2,3,4,5,6,7,8,9,10]

作用在向量上的函数

Recall the idea of vector spaces $\mathbb{R}^n$. The dot product is a binary operation of vectors

$ (\cdot) : \mathbb{R}^n \rightarrow \mathbb{R}^n \rightarrow \mathbb{R}. $

Definition:

A function $T : \mathbb{R}^n \rightarrow \mathbb{R}^n$

is a linear transformation or linear operator of $\mathbb{R}^n$ if

$ T(x + y) = Tx + Ty $ for all $x,y \in \mathbb{R}^n$

and $T(cx) = cTx$ for all $c \in \mathbb{R}, x \in \mathbb{R}^n$.

In this case, a matrix is function!

Definition:

Let $T : \mathbb{R}^n \rightarrow \mathbb{R}^n$ be a linear transformation. Then $T$ is called an orthogonal operator if,

$ Tx \cdot Tx = x \cdot y $

for all $x, y \in \mathbb{R}^n$.

For example, let vector $u \in \mathbb{R}^2$. Then for linear operator $T : \mathbb{R}^2 \rightarrow \mathbb{R}^2$, let

$

T = \begin{bmatrix}

1 & 0 \\\\

0 & -1

\end{bmatrix},

$

then $Tu$ would be the reflection uf $u$ around the x-axis. A 3-by-3 matrix would be the function that map a 3D vector to another vector in 3D space.

作用在图像上的函数

Function can also act on figures! Consider a right pentagon, number all its angle with number 1 to 5. Define $ x : Pentagon \rightarrow Pentagon $ which rotate the pentagon by $2\pi/n$ around its center. Define $ y : Pentagon \rightarrow Pentagon $ which rotate the pentagon by $\pi$ about vertical.


Let $x^2$ be the composition of two $x$, then same idea for all $x^n$, $y^n$. Then we notice that

  • $x^5$ is the same as $\mathbb{1}$,
  • $x^6$ is the same as $x$,
  • $y^2$ is the same as $\mathbb{1}$,
  • $y^3$ is the same as $y$,
  • $yx$ is the same as $x^4y$.

Then we can find the set of all functions of this pentagon,

$ \\{ \mathbb{1}, x, x^2, x^3, x^4, y, xy, x^2y, x^3y, x^4y \\}. $

作用在函数上的函数

When we talk about functional programming, there is a feature called function as first-class citizenship . That means function is just data, no difference than other types of data. Therefore, of course we can pass function as parameters and return a function as output.

JavaScript, Python3, Go all support this feature.

Definition:

A higher-order function is a function that either (can be both)

  • takes function as input parameter,
  • return function as output.

This design is for another true purpose of function programming: reuse the existing functions as much as possible to reduce the complexity of code.

Composition

One great example is the composition operator. Composition is just a binary operation between functions. Let $A,B,C$ be sets, then

$ \circ : (B \rightarrow C) \rightarrow (A \rightarrow B)

\rightarrow (A \rightarrow C) $

where $f \circ g\ x = f(gx)$.

That is, the operator $\circ$ takes a function that map $A$ to $B$ and a function that map $B$ to $C$, then return a function that map $A$ to $C$.

In Haskell, we define the composition operator as

(.) :: (b -> c) -> (a -> b) -> a -> c
f . g x = f (g x)

让函数最用在列表上

Haskell also provides other useful higher-order functions. One is

$ map : (A \rightarrow B) \rightarrow [A] \rightarrow [B]. $

As this type signature suggests, it takes a function and map $A$ to $B$ and a list $A$, apply this function to all elements of $A$ to get a list of $B$.

map :: (a -> b) -> [a] -> [b]

which runs as

Prelude> map (1+) [1..10]
[2,3,4,5,6,7,8,9,10,11]
Prelude> map (read :: String -> Int) ["1","2","3","4","5"]
[1,2,3,4,5]
Prelude> map (show :: Int -> String) [1..5]
["1","2","3","4","5"]

Another one is

$ filter : (A \rightarrow Bool) \rightarrow [A] \rightarrow [A] $

takes two parameters

  • a function map from type $A$ to a boolean
  • and a list of $A$.

When a function outputs a boolean value, we can view it as a "condition". If the condition is satisfied (i.e. `True`), `filter` takes this value.

In Haskell, `filter` is defined as

filter :: (a -> Bool) -> [a] -> [a]
Prelude> filter even [1..10]
[2,4,6,8,10]
Prelude> filter odd [1..10]
[1,3,5,7,9]

Using three of them together, we can get

Prelude> map (even . read) ["1", "2", "3", "4", "5"]
[False,True,False,True,False]
Prelude> filter (even . read) ["1", "2", "3", "4", "5"]
["2","4"]
Prelude> filter id (map (even . read) ["1", "2", "3", "4", "5"])
[True,True]

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码