Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active October 20, 2015 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidev275/0a609cb18b8ba99f4ef4 to your computer and use it in GitHub Desktop.
Save reidev275/0a609cb18b8ba99f4ef4 to your computer and use it in GitHub Desktop.
Example of a constraints problem using Maybe and function composition
let mustBeFourDigits x =
if x > 999 && x < 10000
then Some x
else None
let mustBeEven x =
if x % 2 = 0
then Some x
else None
let firstDigitMustEqualLast x =
let str = x.ToString()
if (str |> Seq.head) = (str |> Seq.last)
then Some x
else None
let constraints =
mustBeFourDigits
>> Option.bind mustBeEven
>> Option.bind firstDigitMustEqualLast
let result = [1000 .. 9999] |> Seq.choose constraints
module Constriants where
import Data.Maybe
mustBeFourDigits x =
if x > 999 && x < 10000
then Just x
else Nothing
mustBeEven x =
if x `mod` 2 == 0
then Just x
else Nothing
constraints x = mustBeFourDigits x >>= mustBeEven
matches = mapMaybe constraints [1000..9999]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment