substring in string in nim (in operator) - substring

I wanted to verify substring existence in a string and came up with:
if "haystack".find("needle") != -1:
But I would have prefered:
if "needle" in "haystack": as in python.
Though we get:
Error: type mismatch: got (string, string) but expected one of: proc
contains[T](s: Slice[T]; value: T): bool proc contains[T](x: set[T];
y: T): bool proc contains[T](a: openArray[T]; item: T): bool
note that if you import strutils it starts to work.

You already gave the answer yourself, import strutils to get the contains proc for strings. Nim automatically used the contains proc for the in operator.

Related

What's wrong when use mypy to check type

from typing import Dict, List, Any, AnyStr, TypeVar
def abc(xyz: str) -> Dict[AnyStr, Any]:
return {"abc": 1}
And I use mypy to check this file. It's giving an Error.
Below is the Error message
"Dict entry 0 has incompatible type "str": "int"; expected "bytes":
"Any""
But I don't know why
The issue is that AnyStr is actually an alias for a typevar. This means your program is actually exactly equivalent to writing:
from typing import Dict, Any, AnyStr, TypeVar
T = TypeVar('T', str, bytes)
def abc(xyz: str) -> Dict[T, Any]:
return {"abc": 1}
This, however, presents us with a problem: how is mypy supposed to infer which of the two possible alternatives you wanted for T?
There are three possible fixes. You can either...
Find some way of using AnyStr at least two or more times within your type signature. For example, perhaps you decide this is really more what you meant?
def abc(xyz: AnyStr) -> Dict[AnyStr, Any]:
# etc
Use Union[str, bytes] instead of AnyStr:
from typing import Union, Dict, Any
def abc(xyz: str) -> Dict[Union[str, bytes], Any]:
# etc
If the type signature is starting to get uncomfortably long, you can shorten it by using a type alias:
from typing import Union, Dict, Any
# Note: this isn't a great type alias name, but whatever
UnionStr = Union[str, bytes]
def abc(xyz: str) -> Dict[UnionStr, Any]:
# etc

What is the return type of a scala if statement without else

I made a mistake similar to the following in some Scala code:
val someVal:String = if (someX == someY) n
In retrospect the mistake is clear to me (it has to assign something to someVal, and if the expression is false, it's probably not going to be a string). I want to know what the value returned would be if the expression is false. My best guess is Unit, or perhaps AnyVal.
That code will not compile, because for someVal to be a String, then each execution path (the if and the else) would have to return a String. However since you don't have an else, this is impossible and thus won't compile.
The compiler error will be the following, which is indicating that you are returning a Unit when you are supposed to return String:
error: type mismatch;
found : Unit
required: String
That's because what you have is equivalent to this:
val someVal: String = if (foo == bar) "Hello World" else ()
() is the only value of Unit, which is not a valid value for a String type.
In the future you can use the Scala repl and have it tell you the types (just don't specify one):
scala> val someVal1 = if (true) "Hello World"
someVal1: Any = Hello World
val someVal2 = if (false) "Hello World"
someVal2: Any = ()
As you can see the type is Any because that is the only common parent between Unit and String:
The type of whole if expression will be the smallest common supertype of all branches.
The true path is String in your example
A missing else is the same as an empty else, both evaluate to Unit.
Unit and String are in completely separate inheritance trees, (String is AnyRef and Unit is AnyVal) so the type of the whole expression is Any, the common super type of all types in Scala.
If the true case resulted in an AnyVal type (for example, Int) then the type of the whole expression would be AnyVal
If the true case evaluated to Unit (for example if you just used println in the if instead of returning a value) then the type of the expression would be Unit which makes sense since both paths have the same type.

Any class in scala

I am beginner in scala language, I am confused with Any class in scala.
def f(x: Any) = println(x)
is above code represents that x variable can be of any datatype(example:int,string etc.)
rewritten code:
def f(x:Any)=x+5
<console>:13: error: type mismatch;
found : Int(5)
required: String
def f(x:Any)=x+5
if x can accept any type then why am I getting above error. I might confused understanding of any in scala. Please correct me.
In a statically typed language you can only call a method m on a value x of type A if m is defined by A. By the nature of Any, there aren't any useful methods on Any that you could call (except a few things like toString or hashCode), certainly no plus operation is defined. Imagine you passed a Boolean into that method, which is allowed since Boolean is a sub-type of Any. If the compiler allowed your code, it would run into a problem, because there is no such thing as + on a Boolean. In a dynamically typed language you could run that code and would then encounter a runtime error.
The error message looks weird, because you can concatenate strings with + and due to an implicit conversion it is possible to concatenate things with strings:
def f(x: Any) = x + "hello" // implicitly converts x to a string
f(true) // "truehello"
This is a source of great confusion and hopefully will disappear from the language. If you used a different method, the error would be more obvious:
def f(x:Any)=x-5
<console>:54: error: value - is not a member of Any
def f(x:Any)=x-5
^
If you look at println() sources you will see:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
where String.valueOf is
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Class Any already has toString method but doesn't have + method (you know that all operators such +, - etc. are methods, see http://tomjefferys.blogspot.com/2011/11/operator-overloading-in-scala.html).

Converting String arguments to Char in Scala

Example code:
object test {
def main(args: Array[String]) {
println(args(0).toChar)
}
}
I have two arguments. The first one is a single letter, whereas the second one is a sequence of letters.
How can I convert the first string argument to Char? I tried the toChar function, but without success (error: value toChar is not a member of String).
args(0).toCharArray converts a string to an array
if you are sure you want only the first char, try args(0).head or more safely: args(0).headOption

What does a "?" symbol (question mark) mean in Scala?

I meet some scala code with "?" but do not know what it mean in scala, could anyone explain it to me ? Thanks.
And here's one example
def getJobId(conf: Configuration): String =
?(conf.get("scoobi.jobid")).getOrElse(sys.error("Scoobi job id not set."))
For me it looks like the apply method of Option. Is there somewhere the following import statement in the code:
import Option.{apply => ?}
This means apply is imported as ?. From the doc of Option.apply:
An Option factory which creates Some(x) if the argument is not null,
and None if it is null.
The whole statement means then:
if conf.get("scoobi.jobid") is not equal null, assign this string,
otherwise assign the string sys.error("Scoobi job id not set.")
returns
It's just a legal character, just like "abcd..."
scala> def ?(i: Int) = i > 2
$qmark: (i: Int)Boolean
scala> val a_? = ?(3)
a_?: Boolean = true
UPD: See Valid identifier characters in Scala , Scala method and values names
UPD2: In the example "?" could be function, method of this or just some object with apply method. It probably returns Option[String].