Skip to content

Instantly share code, notes, and snippets.

@MarcoSero
Created August 25, 2014 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcoSero/7ad9ddc369505de3a7ba to your computer and use it in GitHub Desktop.
Save MarcoSero/7ad9ddc369505de3a7ba to your computer and use it in GitHub Desktop.
Haskell case additions
separatedWords :: String -> [String]
separatedWords = filter (not . any isSpace) . groupBy ((==) `on` isSpace)
toCamel :: String -> String
toCamel = foldl (\acc x -> acc ++ [(if null acc then (head x) else (toUpper $ head x))] ++ (tail x)) [] . separatedWords . map (toLower)
toSnake :: String -> String
toSnake = foldr (\x acc -> x ++ (if null acc then "" else "_") ++ acc) [] . separatedWords . map (toLower)
@atosatto
Copy link

I don't know if it still works for you, but here you are a more readable but still in-liner version of your functions. 😉

import Data.List (groupBy)
import Data.Char (isSpace, toUpper, toLower) 
import Data.Function (on)

separateWords ::  String -> [String]
-- separateWords = filter (not . any isSpace) . groupBy ((==) `on` isSpace)
separateWords = map (filter (not . isSpace)) . words

capitalize :: String -> String
capitalize "" = ""
capitalize s = [toUpper $ head s] ++ tail s

toCamel :: String -> String
-- toCamel = foldl (\acc x -> acc ++ [(if null acc then (head x) else (toUpper $ head x))] ++ (tail x)) [] . separatedWords . map (toLower)
toCamel str = foldl (++) x (map capitalize xs) where x:xs = separateWords (map toLower str)

toSnake :: String -> String
-- toSnake = foldr (\x acc -> x ++ (if null acc then "" else "_") ++ acc) [] . separateWords . map (toLower)
toSnake = map (\x -> if isSpace x then '_' else toLower x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment