How to define a single byte variable in go lang - variables

I am a newbie to golang and want to find a way to define a single byte variable.
It's a demo program in Effective Go reference.
package main
import (
"fmt"
)
func unhex(c byte) byte{
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
func main(){
// It works fine here, as I wrap things with array.
c := []byte{'A'}
fmt.Println(unhex(c[0]))
//c := byte{'A'} **Error** invalid type for composite literal: byte
//fmt.Println(unhex(c))
}
As you see I can wrap a byte with array, things goes fine, but How can I define a single byte without using array? thanks.

In your example, this would work, using the conversion syntax T(x):
c := byte('A')
Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.
See this playground example.
cb := byte('A')
fmt.Println(unhex(cb))
Output:
10

If you don't want to use the := syntax, you can still use a var statement, which lets you explicitly specify the type. e.g:
var c byte = 'A'

Related

Rego - assign array to existing array

I'm getting a weird behavior in Rego and I wonder why does it happen.
Link to Rego Playground
When I create an empty array, and than assign to it new array, the count of the first array is still zero:
package play
x[{"msg": msg}]{
c := []
a := [1,2]
b := [3,4]
c = array.concat(a,b)
count(c) > 0
msg := "Length of c is greater than zero"
}
And the output is:
{
"x": []
}
So, I have 2 questions:
Why do I get false in the line count(c)> 0?
How can I assign array to existing one? ( I need it because I have function that returns array and I'm trying to return the concatenation of 2 arrays. e.g.:
func[{"msg": msg}] = c{
a := [1,2]
b := [3,4]
c = array.concat(a,b)
}
Thanks!
Rego values and variables are immutable, so there's no way to assign a new value to an already existing variable. Your example compiles due to using the unification operator (=) rather than the assignment operator (:=).
In the example you provided, simply remove the first assignment:
package play
x[{"msg": msg}]{
a := [1,2]
b := [3,4]
c := array.concat(a,b)
count(c) > 0
msg := "Length of c is greater than zero"
}

Using in operator to compare string with range of strings

I am using in operator to check whether a value is in range. But I am not able to understand exactly how the comparison with range of strings is done. Below are the few arguments and their output which I have tried:
println("KOTLIN" in "J".."K")
false
println("KOTLIN" in "Java".."Scala")
true
println("KOTLIN" in "Java".."Bhuv")
false
in is compiled down to the following function (defined in kotlin.ranges.Range.kt):
public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive
So "KOTLIN" in "J".."K" results in:
("J".."K").contains("KOTLIN")
The comparison in this case relies on normal String comparisons since >= and <= are compiled down to variations of compareTo. The implementation looks as follows:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
So, "KOTLIN" in "Java".."Scala" is equal to the following:
"KOTLIN".compareTo("Java") >=0 && "KOTLIN".compareTo("Scala") <= 0
Based on your question, I think you are confused about this result:
println("KOTLIN" in "J".."K") is false
Basically, if you were to sort these using Java's String comparison implementation, you would see this:
Bhuv
J
Java
K
KOTLIN
KZ
Since K is lexicographically before KOTLIN, the result you are seeing makes total sense.
Lexicographic Order aka Dictionary Order, e.g.. when scrolling down the words in a dictionary, the order of the words will be
1.Java
2.Kotlin
3.Scala
Hence,
(Kotlin in Java..Scala) will return true.
In normal english, the code above is stating that by using the Dictionary Order, the word Kotlin is found in between the word Java and Scala.

I need to compare property values in StringTemplate

I have a list of tuples that I need to emit a C-like boolean expression from:
ranges = [('a','z'),('0','9'),('_','_')]
my template:
"$ranges:{'$it.0$'<=c&&c<='$it.1$'}; separator='||'$"
this outputs:
'a'<=c&&c<='z'||'0'<=c&&c<='9'||'_'<=c&&c<='_'
I would like to check if $it.0$ is the same as $it.1$ and output c==='$it.0$' in this case (in my example this would generate c==='_' for the last tuple). Is this possible?
You can't have any computation in the template (see Stringtemplate compare strings does not work).
A possible way of getting around this would be to use a custom Range class, and store the functionality inside that. Then you could call a method on the range object that returned whether or not the from and to values are equal.
$ranges:{ range | $if(range.fromToEqual)$c === '$range.from$'$else$'$range.from$' <= c && c <= '$range.to$'$endif$}; separator=" || "$
where the method in the Range class is as follows:
public boolean getFromToEqual() { // note the 'get' prefix
return from == to;
}
output:
'a' <= c && c <= 'b'||'1' <= c && c <= '9'|| c === '_'

Objective c - Letter & Points Model

I'm developing a word game and basically I want to assign an integer value to each character of the alphabet.
Currently, I have a helper to return the value for each char but I'm wondering how I should construct the initial data structure.
At the moment it is a dictionary containing each of the letters of the alphabet as the key and I want the points to be the object for that key. What is the best practise to set the points object?
I want to avoid things like this:
if (_letter == 'a' || _letter == 'A') _points = 1;
else if (_letter == 'b' || _letter == 'B') _points = 4;
else if (_letter == 'c' || _letter == 'C') _points = 3;
Many Thanks
You could use a 26-element C array of integers, where each integer is the point value of that letter, with the 0th element being A, the 1st element being B, etc. You then just lowercase the letter before subtracting 'a' from it and use that as the index into the array. At this point, the only thing left is to prevent non-ASCII-alphabetic characters from being considered, which can be done with a simple range check after lowercasing (if (c >= 'a' && c <= 'z')).
You can take advantage of the fact that chars are integers in C (and therefore Objective-C as well), and simply have an array of ints, keyed off the lowercase version of the char - 'a', like so:
int *letterValues[] = {1,4,3}; // a = 1, b=4, etc...
char thisChar = 'B';
int thisCharVal = letterValues[tolower(thisChar) - 'a'];
Note that this uses tolower, which is declared in (std library), and that subtracting 'a' from a lowercase alpha char is essentially deducing it's "index" in the alphabet: 'a' - 'a' = 0, the "first" item, 'b'-'a' = 1, etc. Therefore, your array initializer ({1,4,3}), is simply the values you want to assign to the chars in order (or use designated initializers if you wish, and you can use chars there as well:
int *letterValues[] = {1,4,3, 'z'=4};
If it's just teh standard latin alphabet, with no umlauts or other special characters, the easiest way is to just make an array of 26 ints for the "point" values:
int LookupPoints(char c)
{
static const unsigned char Points[26]={1,4,3, ... };
c=c|0x20; /* all lower case */
assert(c>='a' && c<='z');
return Points[c-'a'];
}
If you want to include other characters you could check for them specifically, or make an alphabetically sorted array of structs (with the character and the value) to search with bsearch.
EDIT: of course, a dictionary will work too. Just use whatever feels like the easiest solution for your specific case.

SML/NJ while loop

I am really new to SML and I can't figure out how to get answer for the same;
It goes something like: 3^4 < 32 but 3^5 > 32 so my answer is 4 (power of 3), similarly if I have numbers 4 and 63 then 4^2<63 but 4^3>63 so my answer is 2(power of 4).
I have come up with the following code
val log (b, n) =
let
val counter = ref b
val value = 0
in
while !counter > n do
( counter := !counter*b
value := !value + 1)
end;
So here value is what I need as my answer but I get a lot of errors. I know I am wrong at many places. Any help would be appreciated.
I can perhaps do this the normal ML way but I want to learnt impure ML also...
fun loghelper(x,n,b) = if x>n then 0 else (1+loghelper((x*b),n,b));
fun log(b,n) = loghelper(b,n,b);
ok so finally here is the correct code for the while loop and it works as well;
fun log (b, n) =
let
val counter = ref b
val value = ref 0
in
while (!counter <= n) do
(counter := !counter*b;
value := !value + 1);
!value
end;
You have several problems in your code:
Errors:
Instead of val log (b, n) = it should be fun log (b, n) =. fun is a convenience syntax that lets you define functions easily. If you wanted to write this with val you would write: val log = fn (b, n) => (it gets more complicated in the cases of recursive functions or functions with multiple curried arguments)
You need a semicolon to separate two imperative statements: ( counter := !counter*b;
value := !value + 1)
value needs to be a ref: val value = ref 0
Logic:
Your function doesn't return anything. A while loop has the unit type, so your function returns () (unit). You probably want to return !value. To do this, you need to add a semicolon after the whole while loop thing, and then write !value
Your while loop condition doesn't really make sense. It seems reversed. You probably want while !counter <= n do
Your base case is not right. Either value should start at 1 (since counter starts at b, and b is b to the first power); or counter should start at 1 (since b to the zeroth power is 1). The same issue exists with your functional version.