camelCaseとcamel_caseの相互変換
30分プログラム、その187。キャメルケース(likeThis)とアンダースコア(_)区切り(like_this)の相互変換。
正規表現を使えば簡単だけれども、あえてそれを使わずに。
使い方
;; アンダースコア区切りからキャメルケースへの変換 gosh> (under->camel "hello_world") "helloWorld" ;; キャメルケースからアンダースコア区切りへの変換 gosh> (camel->under "helloWorld") "hello_world"
ソースコード
#! /opt/local/bin/gosh ;; -*- mode:scheme; coding:utf-8 -*- ;; ;; camel.scm - ;; ;; Copyright(C) 2007 by mzp ;; Author: MIZUNO Hiroki ;; http://mzp.sakura.ne.jp/ ;; ;; Timestamp: 2007/11/20 22:56:42 ;; ;; This program is free software; you can redistribute it and/or ;; modify it under the same terms as Scheme itself. ;; (use srfi-1) (use srfi-11) (use srfi-13) ;; split camelString to words (define (split-camel s) (define (f camel) (let-values (((hd tl) (break char-upper-case? (cdr camel)))) (let1 hd2 (cons (car camel) hd) (if (eq? tl '()) (list hd2) (cons hd2 (f tl)))))) (map list->string (f (string->list s)))) ;; camelCase -> underline_separate_style (define (camel->under s) (string-join (map string-downcase (split-camel s)) "_")) ;; underline_separate_style -> camelCase (define (under->camel s) (let1 lst (string-split s "_") (string-join (cons (car lst) (map string-titlecase (cdr lst))) "")))