4

I am trying to use map with (string-split "a,b,c" ",") to split strings in a list.

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

Following works if string-split is used without ",":

(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"))

But following does not split strings in the list around ",":

(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"))

How can I use map with functions that need additional arguments?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
rnso
  • 23,686
  • 25
  • 112
  • 234

2 Answers2

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)

Here (curryr string-split ",") is string-split where the last argument is always ",".

soegaard
  • 30,661
  • 4
  • 57
  • 106
1

map applies a procedure of n arguments to the elements of n lists. If you wish to use a procedure that takes other arguments, you need to define a new procedure, which may be anonymous, to call your original procedure with the required arguments. In your case, this would be

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

as @leppie already pointed out.

Michael Vehrs
  • 3,293
  • 11
  • 10