2016-07-26 154 views
3

我試圖使用(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")) 

哪有我使用需要額外參數的函數的地圖?

+3

'(map(lambda(x)(string-split x「,」))lst)' – leppie

+0

最簡單!你應該輸入它作爲答案。 – rnso

回答

4
#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,其中最後一個參數 總是","

+1

選項4:使用'srfi/26'中的'cut'。 –

+1

第一次聽到咖喱! – rnso

+1

選項5:需要['fancy-app'](https://github.com/samth/fancy-app),使用'(map(string-split _「,」)samples)'' –

1

mapn參數的過程應用於n列表的元素。如果您希望使用其他參數的過程,則需要定義一個新的過程(可能是匿名的),以使用所需的參數調用原始過程。在你的情況下,這將是

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

@leppie已經指出。

相關問題