What's the purpose of Just in Elm? - functional-programming

So, I have been doing the Elm track on Exercism.org and I just finished the exercise about the Maybe concept, but one thing is not clear to me yet. What is the purpose of the Just in the definition of Maybe?
type Maybe a = Nothing | Just a
For example, what's the difference between Int and Just Int and why an integer is not considered a Just Int if I don't add the Just word before?
More concretely, when I was trying to solve the RPG problem my first trying resulted in something like this:
type alias Player =
{ name : Maybe String
, level : Int
, health : Int
, mana : Maybe Int
}
revive : Player -> Maybe Player
revive player =
case player.health of
0 ->
if player.level >= 10 then
Player player.name player.level 100 100
else
Player player.name player.level 100 Nothing
_ ->
Nothing
Just to find out that my mistake was in the if statement, that should return Just Person, i.e.:
if player.level >= 10 then
Just (Player player.name player.level 100 (Just 100))
else
Just (Player player.name player.level 100 Nothing)

If you're coming from a background of dynamic typing like Python then it's easy to see it as pointless. In Python, if you have an argument and you want it to be either an integer or empty, you pass either an integer or None. And everyone just understands that None is the absence of an integer.
Even if you're coming from a poorly-done statically typed language, you may still see it as odd. In Java, every reference datatype is nullable, so String is really "eh, there may or may not be a String here" and MyCustomClass is really "eh, there may or may not really be an instance here". Everything can be null, which results in everyone constantly checking whether things are null at every turn.
There are, broadly speaking, two solutions to this problem: nullable types and optional types. In a language like Kotlin with nullable types, Int is the type of integers. Int can only contain integers. Not null, not a string, not anything else. However, if you want to allow null, you use the type Int?. The type Int? is either an integer or a null value, and you can't do anything integer-like with it (such as add it to another integer) unless you check for null first. This is the most straightforward solution to the null problem, for people coming from a language like Java. In that analogy, Int really is a subtype of Int?, so every integer is an instance of Int?. 3 is an instance of both Int and Int?, and it means both "this is an integer" and also "this is an integer which is optional but exists".
That approach works fine in languages with subtyping. If your language is built up from a typical OOP hierarchy, it's easy to say "well, T is clearly a subtype of T?" and move on. But Elm isn't built that way. There's no subtyping relationships in Elm (there's unification, which is a different thing). Elm is based on Haskell, which is built up from the Hindley-Milner model. In this model, every value has a unique type.
Whereas in Kotlin, 3 is an instance of Int, and also Int?, and also Number, and also Number?, and so on all the way up to Any? (the top type in Kotlin), there is no equivalent in Elm. There is no "top type" that everything inherits from, and there is no subtyping. So it's not meaningful to say that 3 is an instance of multiple types. In Elm, 3 is an instance of Int. End of story. That's it. If a function takes an argument of type Int, it must be an integer. And since 3 can't be an instance of some other type, we need another way to represent "an integer that may or may not be there".
type Maybe a = Nothing | Just a
Enter optional typing. 3 can't be an optional integer, since it's an Int and nothing else. But Just 3, on the other hand... Just 3 is an entirely different value and its type is Maybe Int. A Just 3 is only valid in situations where an optional integer is expected, since it's not an Int. Maybe a is what's called an optional type; it's a completely separate type which represents the type a, but optional. It serves the same purpose and T? in a language like Kotlin, but it's built up from different foundations.
Getting into which one is better would derail this post, and I don't think that's important here. I have my opinions, but others have theirs as well. Optional typing and nullable typing are two different approaches to dealing with values that may or may not exist. Elm (and Haskell-like languages) use one, and other languages might use the other. A well-rounded programmer should become comfortable with both.

Why an integer is not considered a Just Int if I don't add the Just word before?
Simply because without the constructor (Just), it's only an integer and not something else. There's no automatic type conversion, you have to be explicit about what you want. Would you also consider allow writing 100 if you meant the single-element list [100]? Soon, you would have no idea what it meant if someone wrote 100.
This is not specific to Maybe and its Just variant, this is the rule for all data types. There is no exception for Maybes, even if the language is confusing - an Int is just an Int, but not a Just Int.

Just in Elm is a tag but in this context you can think of it like a function that takes a value of type Int, and return something of the type Maybe Int.

type Maybe a = Nothing | Just a
---
Just 123 -- is a `Maybe Int`
Means Maybe is a type with an associated generic type a. Similar to C++'s T
template <class T>
class Maybe
using MaybeInt = Maybe<Int>
All Nothing and Just a are are functions (aka constructors) to make a Maybe. In Python it might look like:
def Nothing() -> Maybe:
return Maybe() # except in elm, it knows the returned Maybe came from a
# Nothing, so there's some machinery missing here
def Just(some_val) -> Maybe:
return Maybe(some_val)
So if a function returns a Maybe, the returned value has to be passed through one of the two Nothing or Just constructors.

Related

Kotlin Bundle.putString not explicitly adding "String" but instead is "String?"

val args = Bundle()
args.putString("type", details.type)
navigator.navigate(context!!, findNavController(), Destination.TYPE, args)
I am quite confused as to why in the receiving fragment when I go to access the arguments I have passed through it is responding with...
val type: String = arguments.getString("type")
The arguments.getString is all underlined red and says "Required String Found String?" But how when I called method "putString"?!?
It is resulting in text not being rendered in the new fragment and I assume this is a nullability issue.
It's a matter of knowledge that is available in the receiving Fragment.
The Fragment is not aware of how its arguments were created (or modified) so it has to assume the "type" key you're looking for might not be in the arguments Bundle. That's why it returns a nullable (String?) result (the null value would mean absent in arguments).
Your fragment might be created in many places in your app and its arguments might have been modified in many places. We have no way of tracking that.
There are different solutions for this problem, depending on your approach in other parts of the code and how "confident" you are in creating of your Fragment.
I would usually choose a solution in which I assume setting the type is mandatory. Therefore if the type is absent - I fail fast. That would mean the Fragment was misused.
val type: String = arguments!!.getString("type")!!
The code above will crash if either:
a) arguments weren't set, or
b) String with type wasn't put in the arguments Bundle.
You are right, that is a : null ability issue.
First you should be sure if you are expecting a value, so try adding "?" or "!!", i would recommend "?", or go with the block of if {} else
To read the string safely you can use:
val type: String = arguments?.getString("type").orEmpty()
The orEmpty call at the end ensures that a valid String is returned even if either arguments or getString() returns null.
The method signature for getString() returns a nullable String. This is because at compile time, the compiler can't know if the value exists in the bundle or not. You will have the same issue when retrieving anything from any Map.
If you know for certain that the value in the bundle or map should exist at the time you call getString(), you can use the !! operator. That's what it's there for. When you know something should always be there, it is appropriate to want an exception to be thrown (in this case KNPE) if it's not there so you can easily find any programming error during testing.
isEmpty() or ?.let aren't helpful in this particular case because they would just be masking a programming error and making it harder to discover or debug.

Ada: What does 'is type access' mean?

I came across this piece of code from my assignment:
procedure Refs is
type Node is
record
Content : Integer;
Name : Character;
end record;
type XNode is access Node;
type NodeArray is array (Positive range 1 .. 5) of XNode;
[...]
And I cant seem to grok it (to the point that I could explain it to my grandmother) even after reading documentation, wiki etc.
Can someone explain in simple terms what that access keyword means ?
I know nothing about Ada, but thankfully the answer is just 3 seconds of Googling away: XNode is an access type for Node. An access type is a type which grants access to dynamically allocated values of another type.
In other words, it is a pointer. But don't confuse this with the C concept of a pointer. Ada pointers are pointer-safe and memory-safe, you cannot, for example, add 1 to it and have it point to a different piece of memory, or have it point to some random address and claim "this memory is now a Node" (aka type casting).
It is more like an object reference in Java, ECMAScript, Python, or Ruby.

Why is fmt.Println not consistent when printing pointers?

I'm an experienced programmer but have never before touched Go in my life.
I just started playing around with it and I found that fmt.Println() will actually print the values of pointers prefixed by &, which is neat.
However, it doesn't do this with all types. I'm pretty sure it is because the types it does not work with are primitives (or at least, Java would call them that, does Go?).
Does anyone know why this inconsistent behaviour exists in the Go fmt library? I can easily retrieve the value by using *p, but for some reason Println doesn't do this.
Example:
package main
import "fmt"
type X struct {
S string
}
func main() {
x := X{"Hello World"}
fmt.Println(&x) // &{Hello World} <-- displays the pointed-to value prefixed with &
fmt.Println(*(&x)) // {Hello World}
i := int(1)
fmt.Println(&i) // 0x10410028 <-- instead of &1 ?
fmt.Println(*(&i)) // 1
}
The "technical" answer to your question can be found here:
https://golang.org/src/fmt/print.go?#L839
As you can see, when printing pointers to Array, Slice, Struct or Map types, the special rule of printing "&" + value applies, but in all other cases the address is printed.
As for why they decided to only apply the rule for those, it seems the authors considered that for "compound" objects you'd be interested in always seeing the values (even when using a pointer), but for other simple values this was not the case.
You can see that reasoning here, where they added the rule for the Map type which was not there before:
https://github.com/golang/go/commit/a0c5adc35cbfe071786b6115d63abc7ad90578a9#diff-ebda2980233a5fb8194307ce437dd60a
I would guess this had to do with the fact that it is very common to use for example pointers to Struct to pass them around (so many times you'd just forget to de-reference the pointer when wanting to print the value), but no so common to use pointers to int or string to pass those around (so if you were printing the pointer you were probably interested in seeing the actual address).

Invoking a primitive operation via dot operator fails

I have a problem understanding how the UFCS (Universal Function Call Syntax) works in Ada.
Let's say I have a type, like:
package People
type Person is tagged private;
-- This procedure is a primitive operation:
procedure Say_Name (Person_Object : in Person);
private
type Person is tagged record
Name : String;
end record;
end People;
then I can call the procedure as if it actually belonged to the Person type:
Some_Person_Instance.Say_Name;
Now that works, but in my particular instance it doesn't make sense to have a record, and a subtype would suffice.
subtype Person is String;
At this point (assuming I changed the procedure's workings), it fails to compile and I get the error:
invalid prefix in selected component "Person".
Why? It doesn't even help if I do:
type Person is new String;
Does UFCS only work for records?
I apologize if this is an inane question, but I've no study materials for Ada (apart for couple of e-books) and the textbook I ordered hasn't arrived yet.
UFCS is a full feature of the D language. For historical reasons, Ada has mixed approaches to calls in different parts of the language.
Ordinary subprogram calls are dealt with in ARM 6.4, and look like Subprogram_Name (Parameters) (or just Subprogram_Name if there are no parameters).
Protected subprogram calls (ARM 9.5.1) and entry calls (ARM 9.5.3) look like Object.Subprogram_Or_Entry_Name (Parameters).
Primitive subprograms of tagged types, however, can be called either way; either as an ordinary call, or, if the tagged parameter is the first parameter, using the prefix notation (ARM 4.1.3(9.1)).
There is discussion of this design in AI95-00252; apparently the designers did consider allowing both call forms for all types, but there were too many complications and too few benefits. A shame, I think we all agree, though perhaps it can be taken too far; the D example (from here)
values.multiply(10).divide(3).evens.writeln;
might be a case in point!
With regard to learning Ada and Web resources, have a look at the Ada Resource Association’s resource list.

What is the model of value vs. reference in Nim?

NOTE: I am not asking about difference between pointer and reference, and for this question it is completely irrelevant.
One thing I couldn't find explicitly stated -- what model does Nim use?
Like C++ -- where you have values and with new you create pointers to data (in such case the variable could hold pointer to a pointer to a pointer to... to data)?
Or like C# -- where you have POD types as values, but user defined objects with referenced (implicitly)?
I spotted only dereferencing is automatic, like in Go.
Rephrase. You define your new type, let's say Student (with name, university, address). You write:
var student ...?
to make student hold actual data (of Student type/class)
to make student hold a pointer to the data
to make student hold a pointer to a pointer to the data
Or some from those points are impossible?
By default the model is of passing data by value. When you create a var of a specific type, the compiler will allocate on the stack the required space for the variable. Which is expected, as Nim compiles to C, and complex types are just structures. But like in C or C++, you can have pointers too. There is the ptr keyword to get an unsafe pointer, mostly for interfacing to C code, and there is a ref to get a garbage collected safe reference (both documented in the References and pointer types section of the Nim manual).
However, note that even when you specify a proc to pass a variable by value, the compiler is free to decide to pass it internally by reference if it considers it can speed execution and is safe at the same time. In practice the only time I've used references is when I was exporting Nim types to C and had to make sure both C and Nim pointed to the same memory. Remember that you can always check the generated C code in the nimcache directory. You will see then that a var parameter in a proc is just a pointer to its C structure.
Here is an example of a type with constructors to be created on the stack and passed in by value, and the corresponding pointer like version:
type
Person = object
age: int
name: string
proc initPerson(age: int, name: string): Person =
result.age = age
result.name = name
proc newPerson(age: int, name: string): ref Person =
new(result)
result.age = age
result.name = name
when isMainModule:
var
a = initPerson(3, "foo")
b = newPerson(4, "bar")
echo a.name & " " & $a.age
echo b.name & " " & $b.age
As you can see the code is essentially the same, but there are some differences:
The typical way to differentiate initialisation is to use init for value types, and new for reference types. Also, note that Nim's own standard library mistakes this convention, since some of the code predates it (eg. newStringOfCap does not return a reference to a string type).
Depending on what your constructors actually do, the ref version allows you to return a nil value, which you can treat as an error, while the value constructor forces you to raise an exception or change the constructor to use the var form mentioned below so you can return a bool indicating success. Failure tends to be treated in different ways.
In C-like languages theres is an explicit syntax to access either the memory value of a pointer or the memory value pointed by it (dereferencing). In Nim there is as well, and it is the empty subscript notation ([]). However, the compiler will attempt to automatically put those to avoid cluttering the code. Hence, the example doesn't use them. To prove this you can change the code to read:
echo b[].name & " " & $b[].age
Which will work and compile as expected. But the following change will yield a compiler error because you can't dereference a non reference type:
echo a[].name & " " & $a[].age
The current trend in the Nim community is to get rid of single letter prefixes to differentiate value vs reference types. In the old convention you would have a TPerson and an alias for the reference value as PPerson = ref TPerson. You can find a lot of code still using this convention.
Depending on what exactly your object and constructor need to do, instead of having a initPerson returning the value you could also have a init(x: var Person, ...). But the use of the implicit result variable allows the compiler to optimise this, so it is much more a taste preference or requirements of passing a bool to the caller.
It can be either.
type Student = object ...
is roughly equivalent to
typedef struct { ... } Student;
in C, while
type Student = ref object ...
or
type Student = ptr object ...
is roughly equivalent to
typedef struct { ... } *Student;
in C (with ref denoting a reference that is traced by the garbage collector, while ptr is not traced).

Resources