cis.upenn.edu cis194 Haskell基础知识:功能和图片 [英] cis.upenn.edu cis194 Haskell Basics: Functions and Pictures
问题描述
现在交通信号灯是绿色的,但是我们希望它不时地切换为红色. CodeWorld API不仅允许我们绘制图形,而且允许运行动画.什么是动画?这是一张随时间变化的图片,其中时间可以方便地理解为自动画开始以来的秒数.
Now the traffic light is green, but we want it to switch to red every now and then. The CodeWorld API not only allows us to draw drawings, but also to run animations. What is an animation? It is a picture that changes over time, where time can conveniently be understood as the number of seconds since the start of the animation.
在命令式语言中,一个人可能会有一个getCurrentTime()
函数,并在我们的图形生成中的某个地方调用它.在纯功能语言中,这是不可能的,也不希望这样做,因为这将是隐藏的副作用.而是将时间作为参数提供.
In imperative language, one would probably have a getCurrentTime()
function and call that from somewhere in our drawing generating. This is not possible nor desirable in a pure functional language, as it would be a hidden side effect. Instead, the time is provided as a parameter.
因此,此代码使交通信号灯每三秒钟切换一次:
So here this codes makes the traffic light switch every three seconds:
trafficController :: Double -> Picture
trafficController t
| round (t/3) `mod` 2 == 0 = trafficLight True
| otherwise = trafficLight False
main :: IO ()
main = animationOf trafficController
问题:
- 如果功能(c1)已定义(如上)与时间参数一起使用,那么在
main
语句中没有输入t
的情况下如何工作? - 是什么使
t
参数始终增加?
- How can the function
trafficController
work without thet
input in themain
statement if it is defined (above) to work with time parameter? - What makes the
t
parameter increment all the time ?
推荐答案
-
animationOf
的类型为(Double -> Picture) -> IO ()
.这意味着其参数必须具有类型Double -> Picture
,即它必须是从Double
到Picture
的函数.trafficController
是具有这种类型的功能.请注意,trafficController t
(对于某些Double
t
)不是:它是Picture
!
animationOf
's type is(Double -> Picture) -> IO ()
. This means its argument has to have typeDouble -> Picture
, i.e. it must be a function fromDouble
toPicture
.trafficController
is a function with precisely this type. Note thattrafficController t
(for someDouble
t
) isn't: it's aPicture
!
The definition of animationOf
, which you can find here. If you look into what it does with its argument, and then the functions it calls, etc., it ultimately calls its parameter (trafficController
in this case) with different t
repeatedly. However, it requires tracing a few steps, and I wouldn't recommend it at this stage.
这篇关于cis.upenn.edu cis194 Haskell基础知识:功能和图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!