Check for differences of two sets in Elm - set

I am trying to check if my set of chars in elm contains only valid chars. If a char is found that is invalid, I return those chars, separated by a comma. What I currently have tries to convert the string to a list of chars, then that list to a set of chars. Then diffs the set with a set of valid chars, not sure where to go after that, I have not written much in Elm before. If no diffs are found then return nothing.
validChars : Set.Set Char
validChars =
Set.fromList <| String.toList " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
validString : String -> Maybe String
validString x =
let
list =
String.toList x
set1 =
Set.fromList list
diffs=
Set.diff set1 validChars
if Set.isEmpty diffs == True
Nothing
The if statement doesn't work in Elms online compiler, it says it is looking for "in"

Your code has a few things wrong with it, here's a version that compiles.
import Set
validChars : Set.Set Char
validChars = Set.fromList <| String.toList " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
validString : String -> Maybe String
validString string =
let
diff =
Set.diff validChars <| Set.fromList <| String.toList string
in
if not <| Set.isEmpty diff then
Just string
else
Nothing
Basically when it said it was looking for in, it wasn't wrong, in is a necessary part of a function when you use let statements.

Related

How do I accept a literal "*" as a command-line argument?

I am writing a very simple command line calculator in rust, getting a number ,an operator, then another number and do the calculation and print the result. To show what I am getting from command args, I have printed them in a loop before the main code. I works fine for plus, minus and division, but for multiplication I get unexpected result, as I print it, instead of a star (*) for multiplication, I get the files list on my current directory.
Here is my rust code, I will appreciate an explanation and if there is any workaround.
use std::env;
fn main(){
let args: Vec<String> = env::args().collect();
for arg in args.iter(){
println!("{}", arg);
}
let mut result = 0;
let opt = args[2].to_string();
let oper1 = args[1].parse::<i32>().unwrap();
let oper2 = args[3].parse::<i32>().unwrap();
match opt.as_ref(){
"+" => result = oper1 + oper2,
"-" => result = oper1 - oper2,
"*" => result = oper1 * oper2,
"/" => result = oper1 / oper2,
_ => println!("Error")
}
println!("{} {} {} = {}", oper1, opt, oper2, result);
}
The wildcard (*) is expanding out. The shell is going to send this out to the program before it even sees what you actually typed
You can read more about here.
To avoid this, you can just wrap it in quotes, like so:
./program 1 "*" 1

Why Kotlin doesn't implement Int.plus(value: String)?

It causes discomfort when you can do that:
val string = " abc "
val integer = 8
val result = string + integer
and can't do:
val result = integer + string
It has hidden meaning or it's an omission?
Kotlin is static typed language and in basicly you can't add String to Integer. But there are possible to overload operators, so we can now.
In case when we want add any object to string, it's clear: every object can be implicitly converted to String (Any#toString())
But in case of Int + smthg it's not so clear, so only Int + kotlin.Number is defined in standard library.
I suggest to use string interpolation:
val result = "${integer}${string}"
Or define own overloaded plus operator:
operator fun Int.plus(string: String): String = string + this

Unintuitive empty formatted string

I want to add a listener mechanism to a Format-based logging facility, and I ended up in a situation where my program is typed by OCaml and compiles, but the formatted string just disappeared, and I don't understand exactly why this happens (it's related to formatters returning unit when they should return something else, but I expected the program not to type-check in that case).
This comes from a real use case; its simplification may however have led into a somewhat contrived program.
The basic need is this: to devise a Format.printf-like function (with variadic arguments) that is easy to use but also allows other formatters to be notified (e.g. duplicating their outputs).
I've been told this is not possible due to typing constraints, and indeed if I further simplify my example below, I do get typing errors, but for some reason the program below does type-check but does not produce the expected result.
open Format
let observers : formatter list ref = ref []
let add_observer o : unit =
observers := o :: !observers
let print_to_fmt (fmt: formatter) (text: ('a, formatter, unit) format) : unit =
Format.fprintf fmt "<";
Format.fprintf fmt text;
Format.fprintf fmt ">#."
let notify text : unit =
List.iter (fun fmt ->
Format.printf "MESSAGE: {";
Format.printf text;
Format.printf "}#.";
print_to_fmt fmt text
) !observers
let buffer = ref ""
let append text _ _ = buffer := text
let print text =
let fmt = Format.make_formatter append (fun () -> ()) in
Format.kfprintf (fun f -> ()) fmt text
let log text =
notify text;
print text
let () =
add_observer (Format.err_formatter);
log "this works";
log "this does not %d" 42;
log "this also works"
Any help on how to (1) change the program to display this does not 42, or (2) an explanation on why the program type-checks when it seems it shouldn't, would be much appreciated.
You're trying to do a very strange magic with formatters, that I would classify as an abuse, honestly. Formatter is a formatted channel, not data, so they impose all problems of channels, like non-persistent data that disappear suddenly.
If you want to have a log function, that will dispatch data between registered formatters, then the following will work:
open Format
let observers : formatter list ref = ref []
let add_observer o : unit =
observers := o :: !observers
let notify (text : string) : unit =
List.iter (fun fmt ->
fprintf fmt "MESSAGE: {%s}#." text) !observers
let log text = ksprintf notify text
let () =
add_observer Format.err_formatter;
log "this works";
log "this does not %d" 42;
log "this also works"
Will rend the following output:
MESSAGE: {this works}
MESSAGE: {this does not 42}
MESSAGE: {this also works}

Swift adding multiple stringByReplacingOccurrencesOfString on one String?

Hello i would like to create a app that changes characters into binary code and i was wondering if there is a way to add multiple stringByReplacingOccurrencesOfString on one String or if i should take another approach to this "Problem".
Here is what i have so far
func textToBinary(theString: String) -> String {
return theString.stringByReplacingOccurrencesOfString("a",
withString: "01100001")
}
textArea.text = textToBinary(lettersCombined)
// lettersCombined is the string that i want to turn into BinaryCode.
Try this:
func textToBinary(theString : String, radix : Int = 2) -> String {
var result = ""
for c in theString.unicodeScalars {
result += String(c.value, radix: radix) + " "
}
return result
}
println(textToBinary("a"))
println(textToBinary("abc", radix: 10))
println(textToBinary("€20", radix: 16))
println(textToBinary("😄"))
(The last one is a smiley face but somehow my browser can't display it).
Edit: if you want to pad your strings to 8-character long, try this:
let str = "00000000" + String(c.value, radix: radix)
result += str.substringFromIndex(advance(str.startIndex, str.characters.count - 8)) + " "
The first line adds eight 0 the left of your string. The second line takes the last 8 characters from the padded string.

Converting Decimal to ASCII Character

I am trying to convert an decimal number to it's character equivalent. For example:
int j = 65 // The character equivalent would be 'A'.
Sorry, forgot to specify the language. I thought I did. I am using the Cocoa/Object-C. It is really frustrating. I have tried the following but it is still not converting correctly.
char_num1 = [working_text characterAtIndex:i]; // value = 65
char_num2 = [working_text characterAtIndex:i+1]; // value = 75
char_num3 = char_num1 + char_num2; // value = 140
char_str1 = [NSString stringWithFormat:#"%c",char_num3]; // mapped value = 229
char_str2 = [char_str2 stringByAppendingString:char_str1];
When char_num1 and char_num2 are added, I get the new ascii decimal value. However, when I try to convert the new decimal value to a character, I do not get the character that is mapped to char_num3.
Convert a character to a number in C:
int j = 'A';
Convert a number to a character in C:
char ch = 65;
Convert a character to a number in python:
j = ord('A')
Convert a number to a character in Python:
ch = chr(65)
Most languages have a 'char' function, so it would be Char(j)
I'm not sure what language you're asking about. In Java, this works:
int a = 'a';
It's quite often done with "chr" or "char", but some indication of the language / platform would be useful :-)
string k = Chr(j);

Resources