cis.upenn.edu cis194 Haskell基础知识:功能和图片 [英] cis.upenn.edu cis194 Haskell Basics: Functions and Pictures

查看:59
本文介绍了cis.upenn.edu cis194 Haskell基础知识:功能和图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在交通信号灯是绿色的,但是我们希望它不时地切换为红色. 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

问题:

  1. 如果功能(c1)已定义(如上)与时间参数一起使用,那么在main语句中没有输入t的情况下如何工作?
  2. 是什么使t参数始终增加?
  1. How can the function trafficController work without the t input in the main statement if it is defined (above) to work with time parameter?
  2. What makes the t parameter increment all the time ?

推荐答案

  1. animationOf的类型为 (Double -> Picture) -> IO () .这意味着其参数必须具有类型Double -> Picture,即它必须是从DoublePicture的函数. trafficController是具有这种类型的功能.请注意,trafficController t(对于某些Double t)不是:它是Picture

  1. animationOf's type is (Double -> Picture) -> IO (). This means its argument has to have type Double -> Picture, i.e. it must be a function from Double to Picture. trafficController is a function with precisely this type. Note that trafficController t (for some Double t) isn't: it's a Picture!

animationOf的定义,您可以在其中找到

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆