F# keyword 'Some' - f#

F# keyword 'Some' - what does it mean?

Some is not a keyword. There is an option type however, which is a discriminated union containing two things:
Some which holds a value of some type.
None which represents lack of value.
It's defined as:
type 'a option =
| None
| Some of 'a
It acts kind of like a nullable type, where you want to have an object which can hold a value of some type or have no value at all.
let stringRepresentationOfSomeObject (x : 'a option) =
match x with
| None -> "NONE!"
| Some(t) -> t.ToString()

Can check out Discriminated Unions in F# for more info on DUs in general and the option type (Some, None) in particular. As a previous answer says, Some is just a union-case of the option<'a> type, which is a particularly common/useful example of an algebraic data type.

Some is used to specify an option type, or in other words, a type that may or may not exist.
F# is different from most languages in that control flow is mostly done through pattern matching as opposed to traditional if/else logic.
In traditional if/else logic, you may see something like this:
if (isNull(x)) {
do ...
} else { //x exists
do ...
}
With pattern matching logic, matching we need a similar way to execute certain code if a value is null, or in F# syntax, None
Thus we would have the same code as
match x with
| None -> do ...
| Some x -> do ...

Related

Why am I forced to return a typed value for None?

Why am I forced to return a typed value for None?
let getHand = function
| Some(card1, card2) -> card1, card2
| None -> // ?
In my case, I want to deal a hand. But it doesn't make sense for me to still deal a hand if no hand exists via Options.
What am I not considering?
What pattern should I be using?
Specifically, if no hand exists, then I want to grab a full deck.
Why would a method yield a complex typed result if no result exists?
| None -> // Why am I still required to yield a typed result
All values in F# have types. Functions do as well.
The getHand function looks like it takes as input an option value. Since an option value is a Discriminated Union, the function must address both cases of possible input. The compiler and the type system helps you do that.
A part of a function's type is its return value. In F#, a function can only have a single return type (this is also true for C#). Thus, you'll need to address both the Some and the None case, and make the function return the same type in both cases. Sometimes, though, that 'same type' can be another Discriminated Union.
From the wording of your question, it sounds like you want to return some cards in both cases, so perhaps return a list of cards:
let getHand = function
| Some(card1, card2) -> [card1; card2]
| None -> []
Here, I've returned an empty list in the None case, but if you wish, you can instead populate the return value with a default list.
An alternative solution to Mark Seemann's answer is to return option as well. You could write (changed because your own function would become trivial):
let getFirstCard = function
| Some (card1, card2) -> Some card1
| None -> None
or better Option.map (fun (card1, card2) -> card1).
The final (and generally bad) solution is to throw an exception on None using Option.get.

F# type definition syntax

I'm working on the '99 problems of F#', and saw the following definition of NestedList:
type 'a NestedList = List of 'a NestedList list | Elem of 'a
I'm a little confused by the syntax here, as normally there is only a type name after the type. Can someone clarify it? Thanks!
This is a discriminated union in a condensed syntax. You can also write it as:
type 'a NestedList =
| List of 'a NestedList list
| Elem of 'a
or
type NestedList<'a> =
| List of NestedList<'a> list
| Elem of 'a
This is using generics, where the type itself is taking another type as an argument.
F# has two ways of specifying a generic type:
C#/.NET style - SomeType<'a, 'b>
OCaml/ML style - ('a * 'b) SomeType
Those are really two ways of saying the same thing and can be used interchangeably. Which one to use is a matter of preference and code standards. Usually people use OCaml style for basic F# types like list, array or option, and C# style for user-defined and BCL ones.
So this is a definition of a generic discriminated union with generic type 'a.
The key idea is that each element has the type 'a.

Hashtable in F#

Is there an alternative to System.Collections.Generic.Dictionary or System.Collections.Hashtable?
I'm unhappy with the former because it returns value using byref, i.e., I need to do the annoying
let x = ref ""
if hashtable.TryGetValue (key, x) then
// Found, value in !x
else
// Not found.
I'm unhappy with the latter because it's not generic.
EDIT. I'd prefer something generic syntactically looking like Map.tryFind, i.e.,
match Hashtable.tryFind k hashtable with
| None -> ... // Not found
| Some v -> ... // Found v.
Out parameters are part of living with the .NET framework. F# does minimize the pain, however, by automatically tuplizing them along with the return value. So, using Dictionary<_,_> you can do:
match d.TryGetValue(key) with
| true, x -> ... //tuple of return value and out parameter
| _ -> ...
See Passing by Reference on MSDN.
You could easily wrap that into an extension:
type System.Collections.Generic.Dictionary<'K, 'V> with
member x.TryFind(key) =
match x.TryGetValue(key) with
| true, v -> Some v
| _ -> None
There are two collection types in F# you should look at:
Collections.Set<'T> Class (F#)
Immutable sets based on binary trees, where comparison is the F#
structural comparison function, potentially using implementations of
the IComparable interface on key values.
Collections.Map<'Key,'Value> Class (F#)
Immutable maps. Keys are ordered by F# generic comparison.
Map has a function you're looking for:
Map.TryFind
Lookup an element in the map, returning a Some value if the element
is in the domain of the map and None if not.

Inconsistent behavior in pattern matching

type Bar = A | B
type Foo = C of Bar | D of Bar
let case = Unchecked.defaultof<Foo>;;
match case with
| C A -> ""
| C B -> ""
| _ -> "Matches";;
match case with
| C A -> ""
| D B -> ""
| _ -> "Throws"
Quickly skimming over the F# Language Spec, nothing about null-test (which I can't do anyway) seemed related and both types seems to be reference type (AFAIK).
I would assume the behavior in the first case to be correct one.
I think all bets are off once you use Unchecked.defaultof<_> (thus the "Unchecked" ;-)). Null isn't considered a valid value for type Foo from an F# perspective (although it is from the .NET perspective), so I don't think that the pattern matching semantics are defined.
What is it that you're trying to do?
So reading the spec, the first hint is here
b) Types with null as an abnormal value. These are types that do
not admit the null literal, but do have null as an abnormal value.
Types in this category are:
o All F# list, record, tuple, function, class and interface types.
o All F# union types apart from those with null as a normal value
(as discussed in the next paragraph).
For these types, the use of the null literal is not directly
permitted. However it is, strictly speaking, possible to generate a
null value for these types using certain functions such as
Unchecked.defaultof. For these types, null is considered an
abnormal value. The behavior of operations with respect to null values
is defined in §6.9.
This does seem to suggest that on passing in a null value for your union could be some sort of undefined behaviour as the value is "abnormal", Section 6.9 isn't particularly helpful
Looking at the definition for _, it seems like you are right that this is a bug - it states
7.1.7 Wildcard Patterns
The pattern _ is a wildcard pattern and matches any input. For
example:
let categorize x =
match x with
| 1 -> 0
| 0 -> 1
| _ -> 0
I think the most relevnat hints though are later on where the compiled methods for DU's are listed
8.5.3 Compiled Form of Union Types for Use from Other CLI Languages
A compiled union type U will have:
· One CLI static getter property U.C for each nullary union
case C. This will get a singleton object representing that case.
· One CLI nested type U.C for each non-nullary union case C.
This type will have instance properties Item1, Item2.... for each
field of the union case, or a single instance property Item if there
is only one field. A compiled union type with only one case does not
have a nested type. Instead, the union type itself plays the role of
the case type.
· One CLI static method U.NewC for each non-nullary union case
C. This will construct an object for that case.
· One CLI instance property u.IsC for each case C that returns
true or false for the case.
· One CLI instance property u.Tag for each case C that fetches
or computes an integer tag corresponding to the case.
From this, you can see that all of the methods for checking are instance methods, which would require non-nullness. Sine null is "abnormal", the generated code doesn't bother checking, so it throws.
I think you could argue that this is infact a bug, based on the definition of _. However, fixing it would require inserting null checks before every DU pattern matching check, which would slow the code down significantly, so I doubt whether this will be fixed
A pattern match against a DU with two cases compiles to an if/else with type tests. If you translate your examples, the behavior is apparent.
match case with
| C A -> ""
| C B -> ""
| _ -> "Matches"
translates to
if (case is C)
...
else
"Matches"
and
match case with
| C A -> ""
| D B -> ""
| _ -> "Throws"
translates to
if (case is D)
...
else //must be C
//check tag BANG! NRE
And kvb's example: match case with | C _ -> "C" | D _ -> "D"
if (case is D)
//...
else //must be C
"C"
I suppose you could view this as a reasonable optimization (vs. if (case is D) {...} else if (case is C) {...} else { MatchFailureException }) given that null behavior is undefined.
Add a third case to Foo and the problem goes away.
The description of the method Unchecked.defaultof ends with the sentence "This function is unsafe in the sense that some F# values don't have proper null values", which is exactly the case here.
Try this:
let isNull = (case = null) ;;
let isNull = (case = null) ;;
---------------------^^^^
stdin(3,22): error FS0043: The type 'Foo' does not have 'null' as a proper value
>
DUs are intended to be immutable and don't have proper null values.
I'm not able to confirm this at the moment, but wouldn't the AddNullLiteral attribute to the types allow the match to succeed?

Using a variable in pattern matching in Ocaml or F#

I have a function of the form
'a -> ('a * int) list -> int
let rec getValue identifier bindings =
match bindings with
| (identifier, value)::tail -> value
| (_, _)::tail -> getValue identifier tail
| [] -> -1
I can tell that identifier is not being bound the way I would like it to and is acting as a new variable within the match expression. How to I get identifier to be what is passed into the function?
Ok! I fixed it with a pattern guard, i.e. | (i, value)::tail when i = indentifier -> value
but I find this ugly compared to the way I originally wanted to do it (I'm only using these languages because they are pretty...). Any thoughts?
You can use F# active patterns to create a pattern that will do exactly what you need. F# supports parameterized active patterns that take the value that you're matching, but also take an additional parameter.
Here is a pretty stupid example that fails when the value is zero and otherwise succeeds and returns the addition of the value and the specified parameter:
let (|Test|_|) arg value =
if value = 0 then None else Some(value + arg)
You can specify the parameter in pattern matching like this:
match 1 with
| Test 100 res -> res // 'res' will be 101
Now, we can easily define an active pattern that will compare the matched value with the input argument of the active pattern. The active pattern returns unit option, which means that it doesn't bind any new value (in the example above, it returned some value that we assigned to a symbol res):
let (|Equals|_|) arg x =
if (arg = x) then Some() else None
let foo x y =
match x with
| Equals y -> "equal"
| _ -> "not equal"
You can use this as a nested pattern, so you should be able to rewrite your example using the Equals active pattern.
One of the beauties of functional languages is higher order functions. Using those functions we take the recursion out and just focus on what you really want to do. Which is to get the value of the first tuple that matches your identifier otherwise return -1:
let getValue identifier list =
match List.tryFind (fun (x,y) -> x = identifier) list with
| None -> -1
| Some(x,y) -> y
//val getValue : 'a -> (('a * int) list -> int) when 'a : equality
This paper by Graham Hutton is a great introduction to what you can do with higher order functions.
This is not directly an answer to the question: how to pattern-match the value of a variable. But it's not completely unrelated either.
If you want to see how powerful pattern-matching could be in a ML-like language similar to F# or OCaml, take a look at Moca.
You can also take a look at the code generated by Moca :) (not that there's anything wrong with the compiler doing a lot of things for you in your back. In some cases, it's desirable, even, but many programmers like to feel they know what the operations they are writing will cost).
What you're trying to do is called an equality pattern, and it's not provided by Objective Caml. Objective Caml's patterns are static and purely structural. That is, whether a value matches the pattern depends solely on the value's structure, and in a way that is determined at compile time. For example, (_, _)::tail is a pattern that matches any non-empty list whose head is a pair. (identifier, value)::tail matches exactly the same values; the only difference is that the latter binds two more names identifier and value.
Although some languages have equality patterns, there are non-trivial practical considerations that make them troublesome. Which equality? Physical equality (== in Ocaml), structural equality (= in Ocaml), or some type-dependent custom equality? Furthermore, in Ocaml, there is a clear syntactic indication of which names are binders and which names are reference to previously bound values: any lowercase identifier in a pattern is a binder. These two reasons explain why Ocaml does not have equality patterns baked in. The idiomatic way to express an equality pattern in Ocaml is in a guard. That way, it's immediately clear that the matching is not structural, that identifier is not bound by this pattern matching, and which equality is in use. As for ugly, that's in the eye of the beholder — as a habitual Ocaml programmer, I find equality patterns ugly (for the reasons above).
match bindings with
| (id, value)::tail when id = identifier -> value
| (_, _)::tail -> getValue identifier tail
| [] -> -1
In F#, you have another possibility: active patterns, which let you pre-define guards that concern a single site in a pattern.
This is a common complaint, but I don't think that there's a good workaround in general; a pattern guard is usually the best compromise. In certain specific cases there are alternatives, though, such as marking literals with the [<Literal>] attribute in F# so that they can be matched against.

Resources