LoginSignup
2

More than 5 years have passed since last update.

inflections で文字列と遊ぼう

Last updated at Posted at 2016-07-02

Stack Builders Inc.が作っているinflectionsというライブラリで遊んでみました。これはRuby on RailsのInflectorを参考にしつつも型安全になるように設計されたライブラリだそうです。これを使うと

> import Text.Inflections
> toDashed "FooBar"
"foo-bar"
> toUnderscore "FooBar"
"foo_bar"
> toCamelCased True "foo_bar"
"FooBar"
> toCamelCased False "foo_bar"
"fooBar"

このようにスネークケースとキャメルケースを変換したり

> parameterize "Hola. ¿Cómo estás?"
"hola-como-estas"

URLセーフな文字列に変換したり出来ます。

parseSnakeCase :: [String] -> String -> Either ParseError [Word]
parseCamelCase :: [String] -> String -> Either ParseError [Word]

といった関数を使えばスネークケースとキャメルケースの文字列を独自のWordという型に変換することが出来ます。

> parseSnakeCase [] "foo_bar"
Right [Word "foo",Word "bar"]

[Word]の値を作ると

> let Right ws = parseSnakeCase [] "foo_bar"
> camelize ws
"FooBar"
> dasherize ws
"foo-bar"
> humanize ws
"Foo bar"
> underscore ws
"foo_bar"

いろんな形式の文字列に変換できます。

あと地味に便利なのがordinal, ordinalizeという関数で

ordinal :: Integer -> String
ordinalize :: Integer -> String
> ordinal 1
"st"
> ordinal 2
"nd"
> ordinal 3
"rd"
> ordinal 4
"th"
> map ordinal [1..10]
["st","nd","rd","th","th","th","th","th","th","th"]

> ordinalize 1
"1st"
> ordinalize 2
"2nd"
> ordinalize 3
"3rd"
> ordinalize 4
"4th"
> map ordinalize [1..10]
["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th"]

この様に数字に序数標識をつけた文字列を返してくれます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2