Last active
November 26, 2018 16:01
-
-
Save orestis/f5ed37783a7a3e0c6b6e51aa9b30c44e to your computer and use it in GitHub Desktop.
Expressive Clojure: https://www.reddit.com/r/Clojure/comments/a08cn4/the_expressive_c17_coding_challenge_in_clojure/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns scratch | |
(:require [clojure.string :as str])) | |
(defn csv-split [line] | |
(str/split line #",")) | |
(defn replace-col [cols idx s] | |
(map-indexed (fn [i x] (if (= i idx) s x)) cols)) | |
(defn index-of [coll value] | |
(first (keep-indexed #(when (= %2 value) %1) coll))) | |
(defn run [input-str col replacement] | |
(let [[header & rows] (str/split-lines input-str) | |
col-idx (index-of (csv-split header) col) | |
output-seq (->> rows | |
(map #(replace-col (csv-split %) col-idx replacement)) | |
(cons [header]))] | |
(->> output-seq | |
(map #(str/join "," %)) | |
(str/join "\n")))) | |
(def input | |
"name,surname,city,country | |
Adam,Jones,Manchester,UK | |
Joe,Doe,Cracow,Poland | |
Michael,Smith,Paris,France | |
Alex,McNeil,Gdynia,Poland") | |
(def output | |
"name,surname,city,country | |
Adam,Jones,London,UK | |
Joe,Doe,London,Poland | |
Michael,Smith,London,France | |
Alex,McNeil,London,Poland") | |
(= output (run input "city" "London")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment