Skip to content

Instantly share code, notes, and snippets.

@tkellogg
Created March 10, 2012 20:14
Show Gist options
  • Save tkellogg/2012928 to your computer and use it in GitHub Desktop.
Save tkellogg/2012928 to your computer and use it in GitHub Desktop.
Some C# & F# code to talk about discriminated unions
public enum LightSwith
{
On,
Dimmed(int intensity),
Off
}
// And to use
var value = GetLightSwitchValue();
switch(value)
{
case On:
TurnOnLight();
break;
case Dimmed(intensity):
DimLightToIntensity(intensity);
break;
case Off:
TurnOffLight();
break;
}
var value = GetLightSwitchValue();
switch(value)
{
case On:
TurnOnLight();
break;
case Dimmed(intensity) =>
{
DimLightToIntensity(intensity)
}
case Off:
TurnOffLight();
break;
}
type LightSwith =
| On
| Dimmed of int
| Off
And to use it, we use pattern matching:
let lightSwitch = getLightSwitchState()
match lightSwitch with
| On ->
turnOnLight()
| Dimmed intensity -> dimLightToIntensity intensity
| Off ->
turnOffLight()
type LightSwitch =
| On
| Off
// And to use it, we use pattern matching:
let lightSwitch = getLightSwitchState()
match lightSwitch with
| On ->
turnOnLight()
| Off ->
turnOffLight()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment