zoukankan      html  css  js  c++  java
  • 《Two Dozen Short Lessons in Haskell》学习(十三)迭代及重复的常规模式

    《Two Dozen Short Lessons in Haskell》(Copyright © 1995, 1996, 1997 by Rex Page,有人翻译为Haskell二十四学时教程,该书如果不用于赢利,可以任意发布,但需要保留他们的copyright)这本书是学习 Haskell的一套练习册,共有2本,一本是问题,一本是答案,分为24个章节。在这个站点有PDF文件。几年前刚开始学习Haskell的时候,感觉前几章还可以看下去,后面的内容越来越难以理解。现在对函数式编程有了一些了解后,再来看这些题,许多内容变得简单起来了。

    初学Haskell之前一定要记住:

    把你以前学习面向过程的常规的编程语言,如Pascal、C、Fortran等等统统忘在脑后,函数式编程完全是不一样的编程模型,用以前的术语和思维来理解函数式编程里的概念,只会让你困惑和迷茫,会严重地影响你的学习进度。

    这个学习材料内容太多,想把整书全面翻译下来非常困难,只有通过练习题将一些知识点串起来,详细学习Haskell还是先看其它一些入门书籍吧,这本书配套着学学还是不错的。

    第十三章 Iteration and the Common Patterns of Repetition

    这一章开始接触平常编程语言中不可想象的无限数据结构,利用iterate函数可以产生一个无限元素的列表。

    iterate

    iterate函数接受2个参数,假设为iterate f x

    第一个参数本身是一个函数,输入为a类型,输出还是a类型。(这里以a是整数来举例)

    第二个参数是一个值(类型为a)

    输出为一个无限列表,列表中的元素都是a类型,第一个元素就是x,第二个元素是f x,第三个元素是f (f x),第四个元素是f (f (f x)......

    例如:

    函数f的定义如下:

    f x = x + 2

    那么iterate f 0就是输出结果:

    [0, 2, 4, 6, 8, ...]

    如果你在ghci交互窗口中试验该命令,则窗口中不停地输出偶数,直到你按CTRL+C才能打断它。

    iterate_list

    解释一下:

    iterate f 0这个函数有2个参数,第一个参数是f,第二个参数是0

    第一个元素就是0,第二个元素调用f 0(即2),第三个元素调用f 2(即4),以此类推

    1 The iterate function

    a delivers an infinite sequence as its value

    b applies a function to the value that function delivers, over and over

    c delivers its second argument as the first element of a sequence

    d all of the above

    2 What value do the following Haskell commands deliver?

    HASKELL DEFINITION • add2 n = n + 2

    HASKELL COMMAND • iterate add2 0

    HASKELL COMMAND • iterate add2 1

    a the biggest number that Haskell can compute

    b nothing — they aren’t proper commands

    c the number that is two more than the starting point

    d one delivers the sequence of even numbers, the other the odds

    3 Use the iterate function to generate the sequence [x0, x1, x2, x3, …] where x0 = 1 and xn+1 = 11xn mod 127.

    a next x = x/127 * 11

       iterate next 1

    b next x = (11*x) ‘mod‘ 127

       iterate next (1/11 ‘div‘ 127)

    c next x = (11*x) ‘mod‘ 127

       iterate next 1

    d none of the above

    =========================================================

    =========================================================

    1 d

    iterate得到一个无限的序列

    不停地调用函数f

    第一个元素的结果作为输入,继续调用函数f,得到第二个元素

    2 d

    在Haskell中可以直接用列表写出一个无限序列:

    [0, 2..]

    也同样可以得到偶数的无限序列

    同理,用[1,3..]可以得到奇数序列

    3 c

    这里实际上就是一个伪随机数生成器,x0就是随机数种子

  • 相关阅读:
    CS027th: 6papers
    MATH026th: 《矩斋筹算丛刻》
    MATH026th: 《古今算学丛书》目录
    Compiler25th005: Excel Compiler
    AIIE25th004: 2020aiie在合肥举办
    AIIE21th003: 2021年第二届国际工业工程和人工智能大会(IEAI 2021)
    ComPiler200004:Library-Oriented Programming
    ComPiler200003:Story-Oriented Programming
    ComPiler200002:Growing a Compiler
    conda
  • 原文地址:https://www.cnblogs.com/speeding/p/2844832.html
Copyright © 2011-2022 走看看