How to read user input in ATS? - ats

In my ATS application, I am trying to read a input string from a user.
Is there any function in ATS that performs similar functionality as scanf function in C.. If not how to get the input from user without integrating ATS with JS or HTML.

Here is a simple way to read from STDIN:
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
implement
main0() =
{
//
val
lines =
streamize_fileref_line(stdin_ref)
//
val () = lines.foreach()(lam x => println! (x))
//
} (* end of [main0] *)

If you compile to C, then scanf is available. Here is a simple example:
#include
"share/atspre_staload.hats"
#staload
"libats/libc/SATS/stdio.sats"
implement
main0() =
{
//
var str1 = #[char][1024]()
var str2 = #[char][1024]()
//
val () = println! ("Enter name: ")
val ec = $extfcall(int, "scanf", "%s", addr#str1)
val () = assertloc (ec != 0)
val str1 = $UNSAFE.cast{string}(addr#str1)
//
val () = println! ("Enter your website name: ")
val ec = $extfcall(int, "scanf", "%s", addr#str2)
val () = assertloc (ec != 0)
val str2 = $UNSAFE.cast{string}(addr#str2)
//
val () = println! ("str1 = ", str1)
val () = println! ("str2 = ", str2)
//
}

Related

Scala/functional/without libs - check if string permutation of other

How could you check to see if one string is a permutation of another using scala/functional programming with out complex pre-built functions like sorted()?
I'm a Python dev and what I think trips me up the most is that you can't just iterate through a dictionary of character counts comparing to another dictionary of character counts, then just exit when there isn't a match, you can't just call break.
Assume this is the starting point, based on your description:
val a = "aaacddba"
val b = "aabaacdd"
def counts(s: String) = s.groupBy(identity).mapValues(_.size)
val aCounts = counts(a)
val bCounts = counts(b)
This is the simplest way:
aCounts == bCounts // true
This is precisely what you described:
def isPerm(aCounts: Map[Char,Int], bCounts: Map[Char,Int]): Boolean = {
if (aCounts.size != bCounts.size)
return false
for ((k,v) <- aCounts) {
if (bCounts.getOrElse(k, 0) != v)
return false
}
return true
}
This is your method, but more scala-ish. (It also breaks as soon as a mismatch is found, because of how foreach is implemented):
(aCounts.size == bCounts.size) &&
aCounts.forall { case (k,v) => bCounts.getOrElse(k, 0) == v }
(Also, Scala does have break.)
Also, also: you should read the answer to this question.
Another option using recursive function, which will also 'break' immediately once mismatch is detected:
import scala.annotation.tailrec
#tailrec
def isPerm1(a: String, b: String): Boolean = {
if (a.length == b.length) {
a.headOption match {
case Some(c) =>
val i = b.indexOf(c)
if (i >= 0) {
isPerm1(a.tail, b.substring(0, i) + b.substring(i + 1))
} else {
false
}
case None => true
}
} else {
false
}
}
Out of my own curiosity I also create two more versions which use char counts map for matching:
def isPerm2(a: String, b: String): Boolean = {
val cntsA = a.groupBy(identity).mapValues(_.size)
val cntsB = b.groupBy(identity).mapValues(_.size)
cntsA == cntsB
}
and
def isPerm3(a: String, b: String): Boolean = {
val cntsA = a.groupBy(identity).mapValues(_.size)
val cntsB = b.groupBy(identity).mapValues(_.size)
(cntsA == cntsB) && cntsA.forall { case (k, v) => cntsB.getOrElse(k, 0) == v }
}
and roughly compare their performance by:
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
// Match
time((1 to 10000).foreach(_ => isPerm1("apple"*100,"elppa"*100)))
time((1 to 10000).foreach(_ => isPerm2("apple"*100,"elppa"*100)))
time((1 to 10000).foreach(_ => isPerm3("apple"*100,"elppa"*100)))
// Mismatch
time((1 to 10000).foreach(_ => isPerm1("xpple"*100,"elppa"*100)))
time((1 to 10000).foreach(_ => isPerm2("xpple"*100,"elppa"*100)))
time((1 to 10000).foreach(_ => isPerm3("xpple"*100,"elppa"*100)))
and the result is:
Match cases
isPerm1 = 2337999406ns
isPerm2 = 383375133ns
isPerm3 = 382514833ns
Mismatch cases
isPerm1 = 29573489ns
isPerm2 = 381622225ns
isPerm3 = 417863227ns
As can be expected, the char counts map speeds up positive cases but can slow down negative cases (overhead on building the char counts map).

How to turn a floating point number into a string in ATS?

Basically, I am looking for a function of the following interface:
fun double2string(x: double): string
which converts a double into a string representation for it. For instance, double2string(3.14) should return "3.14".
Sometimes I choose following cheat:
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
%{^
#include <assert.h>
char *double2string(double x) {
#define DECIMAL 8
#define DECIMAL_FORMAT "%.8e"
#define DECIMAL_LEN DECIMAL+2+5
char *s = malloc(DECIMAL_LEN+1);
assert(NULL != s);
memset(s, 0, DECIMAL_LEN+1);
snprintf(s, DECIMAL_LEN, DECIMAL_FORMAT, x);
return s;
}
%}
extern fun double2string (x: double): strptr = "mac#"
implement main0 () = {
val s = double2string 1234567890.1234567890
val () = println! s
val () = free s
}
There is a function of the name atspre_string_make_snprintf in ATSLIB for constructing strings. For instance, one can do:
#include
"share/atspre_staload.hats"
fun
double2string(x: double): string =
$extfcall
(
string, "atspre_string_make_snprintf", "%.8e", x
) (* double2string *)
implement
main0() =
println! ("Pi = ", double2string(3.1415926535))
What is returned by atspre_string_make_snprintf is a linear string (strptr), which can be freed:
fun double2strptr(x: double): Strptr1 = $extfcall(...)
When compiling, please remember to pass the flag -latslib. You can try this example on-line:
https://glot.io/snippets/ejm6ous1fh
For compiling to JavaScript, 'String' can be called to do this. Actually, 'String' turns any given object into some form string representation for it.
Here is a quick way to do it:
fun
double2string
(
x0: double
) : string = let
val i0 = g0float2int_double_int(x0)
val d0 = g0float2int_double_int(100000000 * (x0 - i0))
val i0_rep = g0int2string(i0)
val d0_rep = g0int2string(d0)
val x0_rep =
string0_append3
($UNSAFE.strptr2string(i0_rep), ".", $UNSAFE.strptr2string(d0_rep))
// end of [val]
val ((*freed*)) = strptr_free(i0_rep)
val ((*freed*)) = strptr_free(d0_rep)
in
strptr2string(x0_rep)
end // end of [double2string]

Swift 1.2, capture character from a word

My problem is how to get character from a word
The result I needed is
DisplayChar("asd",1)
and it will display "a"
func DisplayChar(word : String, number : Int) -> String{
let i: Int = count(word)
var result = 0
result = i - (i - number)
var str = ""
var j = 0
for j = 0; j < result; j++ {
str = str + word[j]
}
return str
}
DisplayChar("xyz", 2)
This code should work
let sentence = "Hello world"
let characters = Array(sentence)
print(characters[0]) // "H"
There are a couple good solutions in this answer that may work, two good ones duplicated below.
Convert to Array
let word = "test"
var firstChar = Array(word)[0] // t
(Note: this assumes a UTF8 or ASCII encoded string, but that is likely fine for school.)
Create Your Own Extension
First an extension of String to handle subscripts:
extension String {
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = startIndex.advancedBy(r.startIndex)
let end = start.advancedBy(r.endIndex - r.startIndex)
return self[Range(start ..< end)]
}
}
Then you can just use:
let word = "test"
var firstChar = word[0] // t
Swift strings have a method called substringToIndex, "asd".substringToIndex(1) will return "a".
I'm not sure if it works on Swift 1.2, though.

Assignment throws error in cool

Compilation of this program throws
compilers#compilers-vm:~/cool/jim$ coolc list.cl
"list.cl", line 7: syntax error at or near ';'
Compilation halted due to lex and parse errors
class List{
item : String;
next : List;
init(i: String, n: List) : List
{
item <- i;
next <- n;
self
};
flattn(): String
{
if( isvoid next )
then
item
else
item.concat( next.flattn())
fi
};
};
class Main inherits IO {
main() : Object{
let hello : String <- "Hello ",
wold : String <- "world ",
newLine : String <- "\n",
unfedined : List,
l : List <- (new List).init(hello,
(new List).init(wold,
(new List).init(newLine, unfedined ) ) )
in
out_string( l.flattn() )
};
};
There must be a block that returns a value for init method.
here
item <- i;
next <- n;
self;
.. must be wrapped in to a block;
init(i: String, n: List) : List
{
{
item <- i;
next <- n;
self;
}
};

Algorithm to generate all variants of a word

i would like to explain my problem by the following example.
assume the word: abc
a has variants: ä, à
b has no variants.
c has variants: ç
so the possible words are:
abc
äbc
àbc
abç
äbç
àbç
now i am looking for the algorithm that prints all word variantions for abritray words with arbitray lettervariants.
I would recommend you to solve this recursively. Here's some Java code for you to get started:
static Map<Character, char[]> variants = new HashMap<Character, char[]>() {{
put('a', new char[] {'ä', 'à'});
put('b', new char[] { });
put('c', new char[] { 'ç' });
}};
public static Set<String> variation(String str) {
Set<String> result = new HashSet<String>();
if (str.isEmpty()) {
result.add("");
return result;
}
char c = str.charAt(0);
for (String tailVariant : variation(str.substring(1))) {
result.add(c + tailVariant);
for (char variant : variants.get(c))
result.add(variant + tailVariant);
}
return result;
}
Test:
public static void main(String[] args) {
for (String str : variation("abc"))
System.out.println(str);
}
Output:
abc
àbç
äbc
àbc
äbç
abç
A quickly hacked solution in Python:
def word_variants(variants):
print_variants("", 1, variants);
def print_variants(word, i, variants):
if i > len(variants):
print word
else:
for variant in variants[i]:
print_variants(word + variant, i + 1, variants)
variants = dict()
variants[1] = ['a0', 'a1', 'a2']
variants[2] = ['b0']
variants[3] = ['c0', 'c1']
word_variants(variants)
Common part:
string[] letterEquiv = { "aäà", "b", "cç", "d", "eèé" };
// Here we make a dictionary where the key is the "base" letter and the value is an array of alternatives
var lookup = letterEquiv
.Select(p => p.ToCharArray())
.SelectMany(p => p, (p, q) => new { key = q, values = p }).ToDictionary(p => p.key, p => p.values);
A recursive variation written in C#.
List<string> resultsRecursive = new List<string>();
// I'm using an anonymous method that "closes" around resultsRecursive and lookup. You could make it a standard method that accepts as a parameter the two.
// Recursive anonymous methods must be declared in this way in C#. Nothing to see.
Action<string, int, char[]> recursive = null;
recursive = (str, ix, str2) =>
{
// In the first loop str2 is null, so we create the place where the string will be built.
if (str2 == null)
{
str2 = new char[str.Length];
}
// The possible variations for the current character
var equivs = lookup[str[ix]];
// For each variation
foreach (var eq in equivs)
{
// We save the current variation for the current character
str2[ix] = eq;
// If we haven't reached the end of the string
if (ix < str.Length - 1)
{
// We recurse, increasing the index
recursive(str, ix + 1, str2);
}
else
{
// We save the string
resultsRecursive.Add(new string(str2));
}
}
};
// We launch our function
recursive("abcdeabcde", 0, null);
// The results are in resultsRecursive
A non-recursive version
List<string> resultsNonRecursive = new List<string>();
// I'm using an anonymous method that "closes" around resultsNonRecursive and lookup. You could make it a standard method that accepts as a parameter the two.
Action<string> nonRecursive = (str) =>
{
// We will have two arrays, of the same length of the string. One will contain
// the possible variations for that letter, the other will contain the "current"
// "chosen" variation of that letter
char[][] equivs = new char[str.Length][];
int[] ixes = new int[str.Length];
for (int i = 0; i < ixes.Length; i++)
{
// We start with index -1 so that the first increase will bring it to 0
equivs[i] = lookup[str[i]];
ixes[i] = -1;
}
// The current "workin" index of the original string
int ix = 0;
// The place where the string will be built.
char[] str2 = new char[str.Length];
// The loop will break when we will have to increment the letter with index -1
while (ix >= 0)
{
// We select the next possible variation for the current character
ixes[ix]++;
// If we have exausted the possible variations of the current character
if (ixes[ix] == equivs[ix].Length)
{
// Reset the current character to -1
ixes[ix] = -1;
// And loop back to the previous character
ix--;
continue;
}
// We save the current variation for the current character
str2[ix] = equivs[ix][ixes[ix]];
// If we are setting the last character of the string, then the string
// is complete
if (ix == str.Length - 1)
{
// And we save it
resultsNonRecursive.Add(new string(str2));
}
else
{
// Otherwise we have to do everything for the next character
ix++;
}
}
};
// We launch our function
nonRecursive("abcdeabcde");
// The results are in resultsNonRecursive
Both heavily commented.

Resources