Convert Json array to list of strings - reason

I am reading this tutorial https://www.stackbuilders.com/blog/nonsense-getting-started-with-reason-and-reason-react/. One of the problems I am facing is that api.noopschallenge.com is now dead. I replaced the API call to this https://random-word-api.herokuapp.com/word?number=20 This works but returns a Json Array. I have to convert the Json Array to list(string).
I modified the decodeWords function as
let decodeWord = (json: Js.Json.t) : list(string) =>
switch(Js.Json.decodeArray(json)) {
| None => []
| Some(array) => Belt.Array.map(Js.Json.decodeString, array)
};
But this gives me error
This has type:
Js.Json.t => option(Js.String.t) But somewhere wanted:
array('a)
How do I convert the Json Array to list(string)?

Two problems:
You've switched the arguments to Belt.Array.map around.´array` should come first.
Since decodeString returns an option(string) instead of just a string, you'll have to deal with the Nones somehow. Using Belt.Array.keepMap is a shorter way of just ignoring them.
let decodeWords = (json: Js.Json.t): list(string) =>
switch (Js.Json.decodeArray(json)) {
| None => []
| Some(array) =>
array->Belt.Array.keepMap(Js.Json.decodeString)->Belt.List.fromArray
};
But using the Js.Json API directly is rather cumbersome. You might want to consider using a third-party json decoding library such as bs-json (disclaimer: authored by me) instead. Then it would be as simple as:
let decodeWords = Json.Decode.(list(string))
Or, if you still want it to return an empty list instead of raising an exception on decode failure:
let decodeWords = Json.Decode.(withDefault([], list(string)))

I think I resolved it myself. but if you know of a better solution then please let me know
let decodeWords = (json: Js.Json.t) : list(string) =>
switch(Js.Json.decodeArray(json)) {
| None => []
| Some(array) => Belt.Array.reduce(array, [], (acc, value) => {
switch(Js.Json.decodeString(value)) {
| None => acc
| Some(v) => [v, ...acc]
}
})
};

Related

Rust: Convert SQL types to Rust automatically using sqlx

I'm new to rust and was working on a generic database viewer app using SQLX. Now I've stumbled upon a problem. While querying like a simple
SELECT * FROM TABLE_NAME
Now the problem is that I don't know the type of rows and columns before hand. So how should I parse the queries?
I've tried the following from this post
for r in row {
let mut row_result: Vec<String> = Vec::new();
for col in r.columns() {
let value = r.try_get_raw(col.ordinal()).unwrap();
let value = match value.is_null() {
true => "NULL".to_string(),
false => {
let mat = value.as_str();
match mat {
Ok(m) => m.to_string(),
Err(err) => {
dbg!(err);
"ERROR".to_string()
}
}
}
};
// println!("VALUE-- {:?}", value);
row_result.push(value);
}
result.push(row_result);
}
The problem is that for some columns it's returning like this. Like for the ID columns
"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004"
and for some i'm getting the following error in the dbg! macro
Utf8Error {
valid_up_to: 2,
error_len: Some(
1,
),
}
Anyone can help me here?
BTW I'm using Postgres so all row types are of PgRow
2: Follow up. I was able to get the types of the columns from the information_schema but the problem seems to be that those will be in String and I couldn't find any way to convert those into rust types, like INT8 -> i64, TEXT -> String. Something like that.

Swift - Reducing a Dictionary of Arrays to a single array of same type using map/reduce/flatmap

Given an input like so:
let m = ["one": ["1","2","3"],
"two":["4","5"]
]
how can I use map/reduce to produce the output like:
["1","2","3","4","5"]
I'm not very swifty, and trying to learn it but I cant seem to figure out an efficient way to do this simple operation. My verbose approach would be like so:
var d = [String]()
for (key, value) in m {
value.forEach { (s) in
d.append(s)
}
}
print(d)
I'm sure this can be a 1 liner, could someone assist?
All you need is a single flatMap:
let result = dict.flatMap { _, values in values }

How to pattern match on a value of type React.Ref.t(Js.Nullable.t('a))

I'm trying to access the DOM element as a JS object.
let navRef = React.useRef(Js.Nullable.null);
let width =
switch (Js.Nullable.toOption(navRef)) {
| None => 0.0
| Some(nav) => ReactDOMRe.domElementToObj(nav)##clientWidth
};
But I have a type eror on navRef inside Js.Nullable.toOption
Error: This expression has type React.Ref.t(Js.Nullable.t('a))
but an expression was expected of type
Js.Nullable.t('b) = Js.nullable('b)
React.Ref.t is an opaque type, hence you can't pattern match on it directly. But you can access the value of the ref using React.Ref.current and then pattern match on that:
let navRef = React.useRef(Js.Nullable.null);
let width =
switch (Js.Nullable.toOption(React.Ref.current(navRef))) {
| None => 0.0
| Some(nav) => ReactDOMRe.domElementToObj(nav)##clientWidth
};

Why is a negative integer not a valid pattern in a macro?

Let us consider a simple enum implementation with a static method that check whether a value has an associated value (the efficiency of the implementation is not to be regarded here):
enum Letter {
Alpha = -1,
A = 0,
B = 1,
C = 2,
}
impl Letter {
pub fn in_enum(value: isize) -> bool
{
match value {
-1 => true,
0 => true,
1 => true,
2 => true,
_ => false,
}
}
}
Now, let us write a macro for building enums with an equivalent in_enum method. The macro below was written with some guidance from the Serde guide for enum deserialization as numbers, in which matching for enum variant values also occurs.
macro_rules! my_enum {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum $name {
$($variant = $value,)*
}
impl $name {
pub fn in_enum(value: isize) -> bool
{
match value {
$( $value => true, )*
_ => false,
}
}
}
}
}
my_enum!(Letter {
Alpha = -1,
A = 0,
B = 1,
C = 2,
});
Playground.
With version 1.18.0, the compiler won't accept the variant with a negative integer.
error: expected pattern, found `-1`
--> src/main.rs:13:24
|
13 | $( $value => true, )*
| ^^^^^^
This seems to happen regardless of how I write this pattern down in the macro, or whether I use i32 or isize for the value method parameter. Changing the fragment specifier of $value to pat is also out of the question: the compiler will refuse to build the enum, even without negative variant values.
error: expected expression, found `-1`
--> src/main.rs:5:26
|
5 | $($variant = $value,)*
| ^^^^^^
What's surprising about this is that it works without using macros, as well as when I discard the Alpha variant.
Why does this happen?
This is a bug in the compiler and is already fixed in the nightly version as of today (Jul 5, 2017), and released in stable version 1.20.0.

Entity Framework linq query

I need help formatting my link query properly, I am using EF 3.5:
Dim mediators = (From m In entity.Mediators _
Where m.MediatorAvailabilities.Available = "Weekends"
Where (m.isActive = True) _
Order By m.Sequence _
Select New RankingCriteria() With { _
.FirstName = m.FirstName, _
.LastName = m.LastName, _
.CompanyName = m.CompanyName, _
.PhoneHome = m.PhoneHome, _
.PhoneWork = m.PhoneWork, _
.PhoneMobile = m.PhoneMobile, _
.Email = m.Email _
}).ToList()
I have a navigation property in Mediators to MediatorAvailabilities I want to do something like what is in where clause above in order to filter my results. It's not letting me navigate to the appropriate column by doing this: m.MediatorAvailabilities.Available.
How do I do this filter properly?
Thanks, Justin.
You will need to use the Any method. I dont know the proper VB syntax, but it should look something like this:
Where m.MediatorAvailabilities.Any(ma => ma.Available = "Weekends")