English 中文(简体)
如何在职能方案拟订中保持时间功能?
原标题:How can a time function exist in functional programming?
  • 时间:2011-09-01 08:26:52
  •  标签:

我现在要承认,我对职能方案编制没有多少了解。 我从这里和那里读过这个问题,因此获悉,在职能方案拟订中,一项职能的产出相同,但同样投入,无论职能多少次。 它完全像一个数学功能,该功能对功能表述中涉及的投入参数的相同价值进行评估。

例如,认为:

f(x,y) = x*x + y; // It is a mathematical function

无论你使用多少次<代码>f(10,4),其价值总是<代码>104。 因此,在您撰写的<代码>f(10,4)时,您可将其替换为104,但不得改变整个表述的价值。 该财产称为

Wikipedia(link

反之,在职能法中,职能的产出价值仅取决于对职能的投入,因此,要求一项功能具有相同价值的两倍,而争论×的两倍将产生相同的结果。

职能方案拟订中是否有时间职能( 现行<>>>/em> 时间)?

  • If yes, then how can it exist? Does it not violate the principle of functional programming? It particularly violates referential transparency which is one of the property of functional programming (if I correctly understand it).

  • Or if no, then how can one know the current time in functional programming?

最佳回答

解释这一点的另一个途径是:没有功能<>>>/em>可进入目前的时间(因为时间不变),但action><>>>可进入目前的时间。 请允许我说,getClocktime是一个不变的(或如果你愿意的话,是无效的)功能,它代表了现在时间的action。 无论何时使用>><>>>>---------------

同样,请说<条码><>印/代码>是一种需要一定时间的表述功能,并打印到专册。 由于功能电话不能用纯功能语言产生副作用,我们想象,这种功能需要时间序列,然后将印刷到青少年的action。 这也是一项真正的职能,因为如果你给它同样的时间,它就会每次回去印刷的action

现在,你怎么能把目前的时间用到青春期? 你们也必须把这两项行动结合起来。 因此,我们如何能够做到这一点? 我们不能仅仅通过<条码>植被/代码>至<条码>>,因为印刷预期会有一个时间序列,而不是一个行动。 但我们可以想象的是,有操作者,>>=,其中combines两项行动,一项行动获得一个时间序列,一项行动作为论点和印刷。 采取上述行动后,结果是......taadaa., 这是一项新行动,目前的时间和印刷时间。 顺便提一下,这在Haskell是如何做到的。

Prelude> System.Time.getClockTime >>= print
Fri Sep  2 01:13:23 東京 (標準時) 2011

因此,从概念上来说,你可以这样看待: 纯功能性方案不执行任何I/O,它界定了一个action,然后运行时间系统实施。action>是每一次的,但执行结果取决于何时执行。

我不知道这是否比其他解释更清楚,但有时会帮助我这样想。

问题回答

是的,不是。

不同的实用方案拟定语文以不同方式解决。

在Haskell(非常纯一)中,所有这种缺陷都必须在“I/O Monad——见here上。

你们可以认为,这是为了在你(世界国家)的职能中获取另一个投入(和产出),或者更容易地成为“确保”的场所,如改变时间。

其他语文 F#刚刚建立了一些杂质,因此,你可以发挥一种功能,为同样的投入回报不同的价值——例如/normal的必备语文。

As Jeffrey Burka mentioned in his comment: Here is the nice introduction to the I/O Monad straight from the Haskell wiki.

在Haskell, 一家名为monad的建筑用来处理副作用。 mon鱼基本上意味着你把价值推向集装箱,并有一些功能将价值从集装箱内的价值到价值。 如果我们的集装箱有:

data IO a = IO (RealWorld -> (a,RealWorld))

我们能够安全地实施综合倡议的行动。 这意味着: 类型<代码>IO的行动是一种功能,其表现为类型的<代码>Real World,并连同其结果重新编号。

背后的想法是,每个国际交易日志的行动都向外部转移,其代表是象征性的<条码>。 利用僧.,我们可以发挥多种功能,使真正的世界团结起来。 mon最重要的功能是>>=,已宣布bind:

(>>=) :: IO a -> (a -> IO b) -> IO b

<代码>>>= 采取一项行动并履行一项职能,采取这一行动并产生新的行动。 回归类型是新的行动。 例如,请预示有以下功能:now • IO String,该功能代表目前时间返回。 我们可以将其与<代码>putStrLn连接起来,将其印成:

now >>= putStrLn

或写在do -Notation上,更熟悉一个必备方案管理员:

do currTime <- now
   putStrLn currTime

All this is pure, as we map the mutation and information about the world outside to the RealWorld token. So each time, you run this action, you get of course a different output, but the input is not the same: the RealWorld token is different.

Most functional programming languages are not pure, i.e. they allow functions to not only depend on their values. In those languages it is perfectly possible to have a function returning the current time. From the languages you tagged this question with this applies to Scala and F# (as well as most other variants of ML).

语言如Haskell Clean,后者完全不同。 在Haskell,目前的时间无法通过一种功能,而是一种所谓的IO行动,即Haskell控制着副作用。

简而言之,它是一种功能,但这一功能将具有世界价值,作为其论点,并因此而重新获得世界的新价值(除目前时间外)。 这种类型的制度将确保每个世界的价值只能一度使用(而消费世界价值的每一功能都会产生新的变化)。 这样,每次都必须有不同的论据来要求时间功能,从而允许每次不同的时间返回。

“经常时间”不是一个功能。 这是一个参数。 如果贵国的法典取决于目前时间,则意味着你的代码按时计。

绝对可以完全以实用的方式做到这一点。 这样做有几种办法,但最简单的做法是,不仅在时间上,而且要在上恢复你所要求的下一次测量职能。

在C#中,你可以这样执行:

// Exposes mutable time as immutable time (poorly, to illustrate by example)
// Although the insides are mutable, the exposed surface is immutable.
public class ClockStamp {
    public static readonly ClockStamp ProgramStartTime = new ClockStamp();
    public readonly DateTime Time;
    private ClockStamp _next;

    private ClockStamp() {
        this.Time = DateTime.Now;
    }
    public ClockStamp NextMeasurement() {
        if (this._next == null) this._next = new ClockStamp();
        return this._next;
    }
}

(考虑到这是一个简单而非实际的例子。) 具体来说,名单的节点可以是收集的垃圾,因为它们是按《Starttime方案》确定的。

这一“ClockStamp”类是不可改变的联系清单,但是实际上,这些点是按需求产生的,因此它们可以控制目前的时间。 任何想要衡量时间的职能都应有锁定的灯泡参数,也必须按其结果恢复最后的测量结果(即电线器不见旧测量),例如:

// Immutable. A result accompanied by a clockstamp
public struct TimeStampedValue<T> {
    public readonly ClockStamp Time;
    public readonly T Value;
    public TimeStampedValue(ClockStamp time, T value) {
        this.Time = time;
        this.Value = value;
    }
}

// Times an empty loop.
public static TimeStampedValue<TimeSpan> TimeALoop(ClockStamp lastMeasurement) {
    var start = lastMeasurement.NextMeasurement();
    for (var i = 0; i < 10000000; i++) {
    }
    var end = start.NextMeasurement();
    var duration = end.Time - start.Time;
    return new TimeStampedValue<TimeSpan>(end, duration);
}

public static void Main(String[] args) {
    var clock = ClockStamp.ProgramStartTime;
    var r = TimeALoop(clock);
    var duration = r.Value; //the result
    clock = r.Time; //must now use returned clock, to avoid seeing old measurements
}

当然,必须把最后的衡量方法从中、从中、从中、从中、从中、从中、从中、从中、从中、从中、从中、从中、从中、从中、从中删除,这当然是不方便的。 藏有多种方式,特别是在语言设计层面。 我想Haskell利用这种骗子,然后通过使用mon子掩盖了这些丑小块。

我感到惊讶的是,没有一个答复或评论提到煤炭或硬币。 通常,在解释有限数据结构时,也提到了硬币,但它也适用于无休止的观测,如在万国邮联登记的时间。 一种隐藏状态的煤炭ge模型;和 硬币模型observing。 (热门上岗模型 施工状态)。

这是被动职能规划中的一个热点议题。 如果您对此类内容感兴趣,请参阅:http://dataalcommons.ohsu.edu/csetech/91/(28页)。

  • Kieburtz, Richard B., "Reactive functional programming" (1997). CSETech. Paper 91 (link)

是的,如果把时间算作一个参数的话,那么纯粹的功能就能够回去。 不同的时间论点、不同的时间结果。 然后形成其他时间职能,并将这些职能与职能(时间)转换(高度排序)的简单词汇结合起来。 由于这种做法是无国籍的,在此时间可以持续(依赖决议),而不是分散,大大boostingmolity。 这种校正是职能反应性方案拟订的基础。

是的。 你们是正确的! 如今或现在或现在,或以任何方式签署这种fl,都不是以某种方式表现出参考性透明度。 但是,根据对汇编者的指令,它被系统束缚了输入。

By output, Now() might look like not following referential transparency. But actual behaviour of the system clock and the function on top of it is adheres to referential transparency.

是的,在职能方案拟订中,可以使用一个略为修改的功能性方案拟订版本,称为“功能性功能性方案”(缺省或主要内容是纯功能性方案)。

In case of getting the time (or reading file, or launching missile) the code needs to interact with the outer world to get the job done and this outer world is not based on the pure foundations of functional programming. To allow a pure functional programming world to interact with this impure outside world, people have introduced impure functional programming. After all, software which doesn t interact with the outside world isn t any useful other than doing some mathematical computations.

Few functional programming programming languages have this impurity feature inbuilt in them such that it is not easy to separate out which code is impure and which is pure (like F#, etc.) and some functional programming languages make sure that when you do some impure stuff that code is clearly stand out as compared to pure code, like Haskell.

Another interesting way to see this would be that your get time function in functional programming would take a "world" object which has the current state of the world like time, number of people living in the world, etc. Then getting time from which world object would be always pure i.e you pass in the same world state you will always get the same time.

Your question conflates two related measures of a computer language: functional/imperative and pure/impure.

一种功能性语言界定了各项职能的投入和产出之间的关系,一种必须使用的语言描述特定业务,以便具体开展工作。

纯语言不会产生或取决于副作用,而一种杂质的语言在整个使用。

One-hundred percent pure programs are basically useless. They may perform an interesting calculation, but because they cannot have side effects they have no input or output so you would never know what they calculated.

To be useful at all, a program has to be at least a smidge impure. One way to make a pure program useful is to put it inside a thin impure wrapper. Like this untested Haskell program:

-- this is a pure function, written in functional style.
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

-- This is an impure wrapper around the pure function, written in imperative style
-- It depends on inputs and produces outputs.
main = do
    putStrLn "Please enter the input parameter"
    inputStr <- readLine
    putStrLn "Starting time:"
    getCurrentTime >>= print
    let inputInt = read inputStr    -- this line is pure
    let result = fib inputInt       -- this is also pure
    putStrLn "Result:"
    print result
    putStrLn "Ending time:"
    getCurrentTime >>= print

You re broaching a very important subject in functional programming, that is, performing I/O. The way many pure languages go about it is by using embedded domain-specific languages, e.g., a sublanguage whose task it is to encode actions, which can have results.

例如,Haskell的操作时间预计我会确定一项名为main<>/code>的行动,由构成我的方案的所有行动组成。 其后,该手术会执行。 多数时候,在这样做时,它执行的是纯粹的法典。 从时间来看,运行时间将使用计算数据进行I/O,并将反馈数据反馈为纯代码。

You might complain that this sounds like cheating, and in a way it is: by defining actions and expecting the runtime to execute them, the programmer can do everything a normal program can do. But Haskell s strong type system creates a strong barrier between pure and "impure" parts of the program: you cannot simply add, say, two seconds to the current CPU time, and print it, you have to define an action that results in the current CPU time, and pass the result on to another action that adds two seconds and prints the result. Writing too much of a program is considered bad style though, because it makes it hard to infer which effects are caused, compared to Haskell types that tell us everything we can know about what a value is.

Example: clock_t c = time(NULL); printf("%d ", c + 2); in C, vs. main = getCPUTime >>= c -> print (c + 2*1000*1000*1000*1000) in Haskell. The operator >>= is used to compose actions, passing the result of the first to a function resulting in the second action. This looking quite arcane, Haskell compilers support syntactic sugar that allows us to write the latter code as follows:

type Clock = Integer -- To make it more similar to the C code

-- An action that returns nothing, but might do something
main :: IO ()
main = do
    -- An action that returns an Integer, which we view as CPU Clock values
    c <- getCPUTime :: IO Clock
    -- An action that prints data, but returns nothing
    print (c + 2*1000*1000*1000*1000) :: IO ()

The latter looks quite imperative, doesn t it?

If yes, then how can it exist? Does it not violate the principle of functional programming? It particularly violates referential transparency

It does not exist in a purely functional sense.

Or if no, then how can one know the current time in functional programming?

了解如何在计算机上检索时间可能首先有用。 基本上存在着跟踪时间的板电路(这是计算机通常需要一个小型电池组的原因)。 然后可能有一些内部程序,确定某个记忆登记册的时间价值。 哪些基本锅炉 down落到一个价值上,由万国邮联收回。


对Haskell而言,有一种概念是,一个国际交易日志的行动,可以用来开展一些国际交易日志的工作。 因此,不提及<代码> 我们参考了<代码>IO Time数值。 所有这些都将是完全有效的。 我们指的是<条码>日,但与的意思大致相同的内容为

When we actually execute the Haskell program, the IO action would actually take place.

It can be answered without introducing other concepts of FP.

Possibility 1: time as function argument

A language consists of

  1. language core and
  2. standard library.

Referential transparency is a property of language core, but not standard library. By no means is it a property of programs written in that language.

Using OP s notation, should one have a function

f(t) = t*v0 + x0; // mathematical function that knows current time

They would ask standard library to get current time, say 1.23, and compute the function with that value as an argument f(1.23) (or just 1.23*v0 + x0, referential transparency!). That way the code gets to know the current time.

Possibility 2: time as return value

Answering OP s question:

Can a time function (which returns the current time) exist in functional programming?

Yes, but that function has to have an argument and you would have to compute it with different inputs so it returns different current time, otherwise it would violate the principals of FP.

f(s) = t(s)*v0 + x0; // mathematical function t(s) returns current time

This is an alternative approach to what I ve described above. But then again, the question of obtaining those different inputs s in the first place still comes down to standard library.

Possibility 3: functional reactive programming

这一设想是:<代码>t(<>t(>>)评价目前与功能t 2搭配的情况。 当现在再次需要使用<代码>t2()时,该编码将行使<代码>t<3>/code>的功能。

(x, t2) = t(); // it s x o clock now
...
(x2, t3) = t2(); // now it s already x2 o clock
...
t(); x; // both evaluate to the initial time, referential transparency!

私营部门司有更多的工作要做,但我认为这超出了禁止化学武器组织的范围。 例如,人们如何要求标准图书馆对一项功能进行认证,并完全以功能性的方式对其收益价值采取行动:一种是附带影响而不是参考性透明度。





相关问题