OCaml
let rec sum = function
| [] -> 0
| h :: t -> h + sum t
match List.hd [] with
| [] -> "empty"
| _ :: _ -> "nonempty"
| exception (Failure s) -> s
Rust
TypeScript
Use never
type Shape = Circle | Square;
function getArea(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
Haskell
-- case of
-- parse country code into country name, returns Nothing if code not recognized
parseCountry :: String -> Maybe String
parseCountry "FI" = Just "Finland"
parseCountry "SE" = Just "Sweden"
parseCountry _ = Nothing
flyTo :: String -> String
flyTo countryCode = case parseCountry countryCode of Just country -> "You're flying to " ++ country
Nothing -> "You're not flying anywhere"