Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Created August 12, 2012 15:24
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 flying-sheep/3332271 to your computer and use it in GitHub Desktop.
Save flying-sheep/3332271 to your computer and use it in GitHub Desktop.
Scala Function & Tuple generator for java
#!/usr/bin/env python3
'''
A script to generate the barebone implementation of scala’s
Function# and Tuple# types for use in java.
I made this to allow Java projects to specify function signatures
which play nice with scala, without depending on scala’s stdlib.
'''
from os.path import basename
#Maximum number of Tuple and Product items, as well as function arguments
MAX_ARGS = 22
INTRO = '''/** This class is generated automatically.
* Run {} to regenerate it. */
package scala;
'''.format(basename(__file__))
FUNC_TEMPLATE = INTRO + '''public abstract class Function{i}<{typeparamsR}> {{
public abstract R apply({args});{tupled}
}}'''
METHOD_TUPLED_TEPLATE = '''
public R tupled(Tuple{i}<{typeparams}> t) {{
return apply({telems});
}}'''
TUPLE_TEMPLATE = INTRO + '''public class Tuple{i}<{typeparams}> {{
{fields}
public Tuple{i}({args}) {{
{assigns}
}}
public boolean equals(Tuple{i}<{objects}> t) {{
return {equal};
}}
public String toString() {{
return "(" + {stradd} + ")";
}}
}}'''
def jsep(fmt, i, sep=', ', extra=None):
'''Returns a joined list of `format` with increasing numbers until i'''
elems = [fmt.format(j) for j in range(1, i+1)]
if extra is not None:
elems.append(extra)
return sep.join(elems)
def create_function(i, fdict):
'''Creates Function<i>.java'''
fdict['typeparamsR'] = jsep('T{}', i, extra='R')
fdict['tupled'] = ''
if i != 0:
fdict['telems'] = jsep('t._{}', i)
fdict['tupled'] = METHOD_TUPLED_TEPLATE.format_map(fdict)
with open('Function{}.java'.format(i), 'w') as function_file:
function_file.write(FUNC_TEMPLATE.format_map(fdict))
def create_tuple(i, fdict):
'''Creates Tuple<i>.java'''
fdict['fields'] = jsep('public T{0} _{0};', i, sep='\n\t')
fdict['assigns'] = jsep('this._{0} = t{0};', i, sep='\n\t\t')
fdict['equal'] = jsep('_{0}.equals(t._{0})', i, sep='\n\t\t\t&& ')
fdict['stradd'] = jsep('_{}', i, sep=' + ", " +')
fdict['objects'] = jsep('Object', i)
with open('Tuple{}.java'.format(i), 'w') as tuple_file:
tuple_file.write(TUPLE_TEMPLATE.format_map(fdict))
def main():
'''Creates all functions and tuples scala provides'''
fdict = {'i': 0, 'args': ''}
create_function(0, fdict)
for i in range(1, MAX_ARGS+1):
fdict['i'] = i
fdict['typeparams'] = jsep('T{}', i)
fdict['args'] = jsep('T{0} t{0}', i)
create_tuple(i, fdict)
create_function(i, fdict)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment