Skip to content

Instantly share code, notes, and snippets.

@mndrix
Last active August 29, 2015 13:55
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 mndrix/8696979 to your computer and use it in GitHub Desktop.
Save mndrix/8696979 to your computer and use it in GitHub Desktop.
Prolog relation between camel-case names and underscore-separated names
:- use_module(library(clpfd)).
:- use_module(library(delay)).
%% under_camel(?Underscore:atom, ?CamelCase:atom) is det.
%
% For example, `under_camel(hello_world, 'HelloWorld')`. Works in both
% directions.
under_camel(U,C) :-
when((ground(U0);ground(U)),prepend_underscore(U, U0)),
delay(atom_codes(U0,U0Codes)),
delay(atom_codes(C,CCodes)),
once(under_camel_(U0Codes,CCodes)).
under_camel_([],[]).
under_camel_([0'_,Lower|Lowers], [Upper|Uppers]) :-
upper_lower(Upper, Lower),
under_camel_(Lowers, Uppers).
under_camel_([Lower|Lowers], [Lower|Uppers]) :-
upper_lower(_,Lower),
under_camel_(Lowers, Uppers).
%% upper_lower(?Upper:integer, ?Lower:integer) is semidet.
%
% True if Upper (uppercase code) and Lower (lowercase code) represent the same letter.
% Useful for bidirection case conversion among ASCII characters.
upper_lower(U,L) :-
U #>= 0'A, U #=< 0'Z,
L #>= 0'a, L #=< 0'z,
L #= U + 32.
%% prepend_underscore(?Without:atom, ?With:atom) is semidet.
%
% True if With has the same content as Without but the former starts
% with an underscore character.
prepend_underscore(Without, With) :-
delay(atom_codes(Without,WithoutCodes)),
delay(atom_codes(With,WithCodes)),
append([0'_],WithoutCodes,WithCodes).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment