// MakeDB // Converts a Scheme database for unicalc, e.g., // (list 'km (make-QL 1.0 '(kilometer) '())) // (list 'kph (make-QL 1.0 '(kilometer) '(hour))) // (list 'kwh (make-QL 1.0 '(hour kilowatt) '())) // (list 'l (make-QL 1.0 '(liter) '())) // (list 'lb (make-QL 1.0 '(pound) '())) // Into Java code to construct the database, e.g., // db.put("km", new Quantity(1.0, 0.0, Arrays.asList("kilometer"), Collections.emptyList())); // db.put("kph", new Quantity(1.0, 0.0, Arrays.asList("kilometer"), Arrays.asList("hour"))); // db.put("kwh", new Quantity(1.0, 0.0, Arrays.asList("hour", "kilowatt"), Collections.emptyList())); // db.put("l", new Quantity(1.0, 0.0, Arrays.asList("liter"), Collections.emptyList())); // db.put("lb", new Quantity(1.0, 0.0, Arrays.asList("pound"), Collections.emptyList())); import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.FileInputStream; class MakeDB { public static void main(String[] args) { try { // Get the filename from the command-line (e.g. "run MakeDB udb.rkt") String fileName = args[0]; // Try to open the file. FileInputStream fin = new FileInputStream(fileName); // Scanners give us a nicer interface to files // (e.g., reading a line at a time) Scanner scan = new Scanner(fin); // We want to check each line of the input file // against a regular expression. Tell Java // about this regular expression Pattern linePat = Pattern.compile( "\\(list '(\\w+)\\s+\\(make-QL\\s+([-0-9.e]+)\\s+'\\(([^)]*)\\)\\s+'\\(([^)]*)\\)\\)\\)"); // Loop over all lines in the file while (scan.hasNextLine()) { // Get the next line String line = scan.nextLine(); // Get ready to start searching this string Matcher m = linePat.matcher(line); // Loop over all pattern matches (database entries) in this line. while (m.find()) { String unitName = m.group(1); String valueString = m.group(2); String numeratorSymbols = m.group(3); String denominatorSymbols = m.group(4); // Display the Java code System.out.println (" db.put(\"" + unitName + "\", new Quantity(" + valueString + ", 0.0, " + makeJavaList(numeratorSymbols) + ", " + makeJavaList(denominatorSymbols) + "));"); } } return; } catch (Exception e) { System.out.println("Missing file, or file not found."); } } // Helper method makeJava list // Given a space-separated list of symbols (a Scheme list without // the parentheses), turn it into Java code to create // a list of strings. private static String makeJavaList(String symbols) { if (symbols.equals("")) { // Zero symbols. Code for an empty list of strings. return "Collections.emptyList()"; } else { // replace whilespace by quote-comma-quote, and add // more double-quotes at the beginning and end. String addCommasAndQuotes = "\"" + symbols.replaceAll("\\s+", "\", \"") + "\""; // Code for a non-empty list of strings return ("Arrays.asList(" + addCommasAndQuotes + ")"); } } }