I'm looking for an Elm function that does the following:
if e then
Just a
else
Nothing
For example, I am looking for an operator (=>) : Bool -> a -> Maybe a (binary function is fine also) that can be used like this
(x == 42) => "yes"
and will return Just "yes" if x == 42 and Nothing otherwise.
Clearly, I can use the if-then-else to accomplish the same thing, but I curious if such a function already exists.
The Elm Fancy Search tool is great for this kind of search. You can type in a function signature or name and see where it is used across all packages listed on package.elm-lang.org.
At the current time, that function signature exists in two packages under the function name when:
krisajenkins/elm-exts/27.4.0: Exts.Maybe.when: When test returns true, return Just value, otherwise return Nothing.
Gizra/elm-essentials/1.2.0: Gizra.Maybe.when: Create a Just a if condition is True, otherwise Nothing
Related
I'm pretty new with Kotlin and I'm trying to figure out Kotlin's scope functions.
My code looks like this:
with(something) {
when {
equals("test") -> var1 = "test123"
startsWith("test2") -> var2 = "test456"
contains("test3") -> myNullableVar?.let { it.var3 = "test789" }
}
}
So before I entered the third check with the .let function my with function does not need to be exhaustive (I'm not returning something, I'm only doing assignments). In my third check I'm using .let as a null-check ... but only for an assignment of it.var3 (if it is not null). I don't need to return anything while I know that Kotlin's .let function returns the result of the body by standard.
Nevertheless now my with/when needs to be exhaustive otherwise it won't compile anymore.
This got me thinking and trying out different things. I found these ways to solve this issue:
I can add an else to my with/when so it becomes exhaustive but actually I don't need an else and I don't want to use it in this case.
I can add another .let, so it looks like this: myNullableVar?.let { it.var3 = "test789" }.let{} .... but this looks kinda hacky to me. Is it supposed to work like this?
Use If(xy==null){...}else{...} stuff but I thought I can solve this with Kotlin differently
Because I'm new with Kotlin I'm not really sure how to handle this case properly. I would probably just go with my second idea because "it works". Or should I don't use .let for null-checks? Add another empty .let{}? Or did I not get the null-safety concept at all? I feel a little bit lost here. Thanks for any help.
This seems to be an unfortunate combination of features…
A when can be non-exhaustive only when it doesn't return a value. The problem is that the with() function does return a value. And since the when is at the bottom, its value is what gets returned, so in this case it must be exhaustive.
So why doesn't it insist on an else branch even if you omit the "test3" branch? That's because assignments don't yield a value. (They evaluate to Unit, which is Kotlin's special type for functions that don't return a useful value.) If every branch gives Unit, then Kotlin seems* to be happy to infer a default branch also giving Unit.
But the "test3" branch returns something else — the type of myNullableVar. So what type does the when infer? The nearest common supertype of that type and Unit, which is the top type Any?. And now it needs an explicit else branch!
So what to do?
You've found a few options, none of which is ideal. So here are a few more, ditto!
You could return an explicit Unit from that branch:
contains("test3") -> { myNullableVar?.let { it.var3 = "test789" }; Unit }
You could return an explicit Unit from the with():
contains("test3") -> myNullableVar?.let { it.var3 = "test789" }
}
Unit
}
You could give an explicit type for the with(). (It has two type parameters, so you'd need to give both, starting with the type of its parameter):
with<String, Unit>("abc") {
I haven't found a single obvious best answer, I'm afraid…
And to answer your last question: yes, ?.let{ is perfectly idiomatic and common for null checks. In this particular case, replacing it with an if happens to solve the type problem:
contains("test3") -> { if (myNullableVar != null) myNullableVar.var3 = "test789" }
But as well as being long-winded, if myNullableVar is a property and not a local variable, then it opens up a race condition (what if another thread sets it to null in between the test and the assignment?) so the compiler would complain — which is exactly why people use let instead!
(* I can't find a reference for this behaviour. Is there an official word on it?)
Given a list of arbitrary objects
input = listOf(a, b, c, a)
... is there a function (with one non-collection argument) in the Kotlin standard library that I can use to make a copy of this list, removing all instances of ONE object?
Something like:
val filtered = input.removeAllInstancesOf(a)
To clarify, I'm aware of other (potential) solutions to this task:
Using the filter function to do this. → val output = input.filterNot { it == a }
Using the minus function with a collection → val output = input.minus(listOf(a))
Using the minus function with a non-collection argument → val output = input.minus(a) ← Only removes the first instance of a!
Removing all instances from a mutable list.
Writing such a function. → Wrap any of the above.
... but I'm wondering why I can't find a function which takes just ONE, non-collection value.
but I'm wondering why I can't find a function which takes just ONE, non-collection value.
Because that's a hyper-specific use-case of the already existing filter function. As you yourself showed it can be done in one line, and is probably the first thing a Kotlin dev would try to do (at least I would). So adding new function to the standard library probably doesn't add much value.
I want to perform an XOR to find if one of two booleans a and b is true but not both. Searching for XOR in Kotlin gave me this answer
infix fun xor(other: Boolean): Boolean
Performs a logical xor operation between this Boolean and the other one. source
I'm still confused on how to implement this
It's an extension that can be invoked on any Boolean. You can use it like this:
true.xor(false)
or this:
true xor false
The last one works since the function is defined as infix.
Other similar extensions defined on Boolean are and, or and not:
//very useful example
true.not().or(true).and(false).xor(true)
find the single number in the array that every element has a duplicate except one.
var a = 0
for (i in numsArray){
a = a xor i
}
return a
eg. input = [2,2,1]
out = 1
I want to have a function that determines if a type is a function type, like this:
isFunction : Type -> Bool
isFunction (a -> b) = True
isFunction _ = False
This returns True for all inputs, however. How can I make this work?
Matching on a Type is known as type-casing. Being able to do this would break a concept called parametricity which is very valuable.
https://stackoverflow.com/a/23224110/108359
Idris does not support type-casing. I think it may have tried at one stage, but people gave up on that quickly. It also used to give errors when type-casing was attempted but the check caused bugs and so has been disabled for now.
While you don't get errors any more, you can't provide an implementation of Type -> Bool which will work differently to const True or const False.
So sorry, this function is not possible. It might sound like a limitation but every time I thought I had a motivation for a function similar to this, I eventually figured out that I could have structured my program in a more explicit way instead.
The question here would be: Why do you need something like this?
Do you need to find out if any arbitrary Idris type is a function or not? Or do you just need to find this out from a specific subset of Idris types?
I can't figure out possible applications for the 1st one, but if it's the 2nd one you need, then you could define your own embedded language for dealing with values with these types, like this:
data Ty = TyNat | TyString | TyFun Ty Ty | ...
isFunction : Ty -> Bool
isFunction (TyFun _ _) = True
isFunction _ = False
Check out this talk for more information about how to implement these kind of embedded languages:
https://vimeo.com/61663317
Almost for the first time I'm trying to write imperative code in ocaml to try to answer a question on this website, but I'm facing a little problem.
let f() =
try
while true do
()
done
with
_ -> 2
He doesn't like this, because he thinks that this function returns unit, as it is in the try block, but the try block returns an int. So it works if I add 3 after "done", but it's really ugly since the 3 is really never returned.
How do you do this ?
Use assert false, which always raises an exception and therefore can be used where any type is expected:
let f() =
try
while true do
()
done;
assert false
with
_ -> 2
while (and for) loops in OCaml are expressions that return a result of type unit.
In addition, when you write (try expr1 with _ -> expr2), this is an OCaml expression of type t, if expr1 and expr2 are well typed of type t (more complicated with polymorphism)
But, in your example, try branch has type unit whereas with branch has type int. The OCaml compiler is not happy with that.