我有以下功能:
def timestamp(key: String) : String = Monoid.combine(key,Instant.now().getEpochSecond.toString)
并想知道,如果它是纯粹的或不是?对我来说一个纯函数是,给定相同的输入返回总是相同的输出.但上面的函数,总是给出相同的字符串将返回另一个字符串与另一个时间,在我看来,它是不纯的.
解决方法
不,我所知道的任何定义都不是纯粹的.关于纯函数的一个很好的讨论在这里:
https://alvinalexander.com/scala/fp-book/definition-of-pure-function.在Alvin对纯度的定义中,他说:
A pure function has no “back doors,” which means:
…
It cannot depend on any external I/O. It can’t rely on input from files,databases,web services,UIs,etc; it can’t produce output,such as writing to a file,database,or web service,writing to a screen,etc.
读取当前系统的时间使用I / O因此它不纯.