Search code examples
schemeracketmap-functionpartial-application

How to use map with a function that needs more arguments


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?


Solution

  • #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 ",".