【问题标题】:How to use map with a function that needs more arguments如何将 map 与需要更多参数的函数一起使用
【发布时间】:2016-11-30 01:32:02
【问题描述】:

我正在尝试使用带有(string-split "a,b,c" ",") 的映射来拆分列表中的字符串。

(string-split "a,b,c" ",")
'("a" "b" "c")

如果在没有“,”的情况下使用字符串拆分,则以下工作:

(define sl (list "a b c" "d e f" "x y z"))
(map string-split sl)
'(("a" "b" "c") ("d" "e" "f") ("x" "y" "z"))

但以下不会拆分列表中“,”周围的字符串:

(define sl2 (list "a,b,c" "d,e,f" "x,y,z"))
(map (string-split . ",") sl2)
'(("a,b,c") ("d,e,f") ("x,y,z"))

如何将 map 与需要额外参数的函数一起使用?

【问题讨论】:

  • (map (lambda (x) (string-split x ",")) lst)
  • 最简单!您应该输入它作为答案。

标签: scheme racket map-function partial-application


【解决方案1】:
#lang racket

(define samples (list "a,b,c" "d,e,f" "x,y,z"))

;;; Option 1: Define a helper

(define (string-split-at-comma s)
  (string-split s ","))

(map string-split-at-comma samples)

;;; Option 2: Use an anonymous function

(map (λ (sample) (string-split sample ",")) samples)

;;; Option 3: Use curry

(map (curryr string-split ",") samples)

这里 (curryr string-split ",")string-split 最后一个参数 总是","

【讨论】:

  • 选项 4:使用来自 srfi/26cut
  • 第一次听说咖喱!
  • 选项5:需要fancy-app,使用(map (string-split _ ",") samples)
【解决方案2】:

mapn 参数的过程应用于n 列表的元素。如果你想使用一个接受其他参数的过程,你需要定义一个新的过程,它可能是匿名的,用所需的参数调用你的原始过程。在你的情况下,这将是

(map (lambda (x) (string-split x ",")) lst)

正如@leppie 已经指出的那样。

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2014-08-28
    • 2019-12-14
    • 2020-02-17
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    相关资源
    最近更新 更多