Example of a constraints problem using Maybe and function composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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