将对追加到球拍/方案中的列表 [英] Append pair to list in racket/scheme

查看:99
本文介绍了将对追加到球拍/方案中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示,我具有 load-mobile-plan 函数,该函数迭代文本并将第n行和n + 1行(n =奇数)构造为一对,然后将其附加到列表.

As shown below, I have the load-mobile-plan function which iterate the text and construct the nth and n+1 lines(n = odd) into a pair, it then append it to a list.

(define temp-pair '())
(define mobile-plan '())

(define load-mobile-plan
  (lambda (file)
    (let [(line (read-line file))]
      (unless (eof-object? line)
        (set! temp-pair (cons line (read-line file)))
        (set! mobile-plan (cons temp-pair mobile-plan))
        (load-mobile-plan file)))))


(call-with-input-file "xxx.txt" load-mobile-plan)



我的问题:
-这在函数式编程中是否合适?我听说函数式编程中的函数不应有副作用,而应仅取决于其自身的输入变量.
-如果是这样,如何修改我的代码以实现相同的目标?



My questions:
-Is this an appropriate method in functional programming? As i heard that function in functional programming should not have side-effects and depends on its own input variables only.
-If so, how to modify my codes to achieve same goal?

推荐答案

在对函数式编程进行调查"几天后,确定,我设法编写了以下代码,与我所讨论的代码具有相同的功能:
OK after few days of "investigation" into functional programming, i manage to code the following, which do the same job as my codes in question:
(define load-mobile-plan
  (lambda (file)
    (let [(mobile-plan '())]
      (read-file file mobile-plan))))


(define read-file
  (lambda (file mobile-plan)
    (let [(line (read-line file))]
      (if [eof-object? line]mobile-plan
          (let* [(temp-pair (cons (string-normalize-spaces line)
                                  (string-normalize-spaces (read-line file))))
                 (mobile-plan (cons temp-pair mobile-plan))]
            (read-file file mobile-plan))))))


(call-with-input-file "xxx.txt" load-mobile-plan)


这篇关于将对追加到球拍/方案中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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