微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

flatmap 最直接的用法

如何解决flatmap 最直接的用法

我已经编写了一个 map一个 flatmap 函数,我正在尝试找出查看 flatmap 函数如何独立工作的最佳方式。这是我的两个定义:

(define (map function lst)
  (if (null? lst)
      ; if we have reached the end of the list,return an empty list
      ; this essentially terminates the list that we are adding below with the cons
      nil
      ; we do a cons -- with the scalar produced by the function call on the current element
      ;                 and the list proceduced by passing the rest of the elements again to the map function
     (cons (function (car lst)) (map function (cdr lst)))))
(define (flatmap function lst)
  (if (null? lst)
      nil
      ; really the only difference here is we do an append instead of a cons
      (append (function (car lst)) (flatmap function (cdr lst)))))

并且调用 map 非常简单,我只是传递给它一个接受单个参数(列表元素)的函数

(map (lambda (x) (* x x)) '(1 2 3 4 5))
; (1 4 9 16 25)

但是,我很难想出一个可以直接传递给 flatmap 函数以查看其工作原理的示例输入/函数。什么是一两个例子可以直接说明它是如何工作的?

解决方法

任何接受单个参数并返回列表的函数都可以。这是您用来演示 %USERPROFILE%\.ssh\config 的函数的变体。

map
,

这里有几个例子:

(flatmap (lambda (x) (list x (* x x))) '(1 2 3 4 5))
; (1 1 2 4 3 9 4 16 5 25)
;;; flattening a list by one-level
(flatmap (lambda (p) p) '((1 2 3) (4 5 6)))
;(1 2 3 4 5 6)
(flatmap (lambda (p) p) '((1 2 (3 4) 5) (6 7 8)))
; (1 2 (3 4) 5 6 7 8)

虽然上面的大部分内容只是使用了 ;;; Map-and-flatten a list at once (flatmap (lambda (p) (cons (* 2 (car p)) (list (* 2(cadr p))) )) '((1 2) (3 4))) ; (2 4 6 8) ; Or could be done with a combination of the two which reads more simply: (map (lambda (x) (* x 2)) (flatmap (lambda (p) p) '((1 2) (3 4)))) ; (2 4 6 8) ;; Possible to do something like (flatmap (lambda (x) (map... ?) to accomplish same? 标识,但我猜总体上似乎毫无用处...

也许一个真正有用的递归展平列表:

lambda (p) p

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。