Skip to content

Instantly share code, notes, and snippets.

@reidev275 reidev275/Constraints.fs
Last active Oct 20, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.