Last active
April 7, 2017 06:27
-
-
Save gaku-sei/9aedf2264d5d4fbfd6120378545c3044 to your computer and use it in GitHub Desktop.
Some fun with Effects in Purescript !
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
exports.random = Math.random; |
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 Random | |
( RANDOM | |
, RandomEff | |
, random | |
, randomInt | |
, randomIndex | |
, randomColor | |
) where | |
import Control.Monad.Eff (Eff) | |
import Data.Array (length, (!!)) | |
import Data.Int (floor, toNumber) | |
import Data.Maybe (Maybe(..), fromMaybe) | |
import Data.String (fromCharArray) | |
import Prelude (bind, pure, ($), (*), (-), (<=), (<>), (<$>), (<<<)) | |
foreign import data RANDOM :: ! | |
type RandomEff fx a = Eff (random :: RANDOM | fx) a | |
foreign import random :: forall fx. RandomEff fx Number | |
randomInt :: forall fx. Int -> RandomEff fx Int | |
randomInt n = (floor <<< (*) (toNumber n)) <$> random | |
randomIndex :: forall fx a. Array a -> RandomEff fx (Maybe a) | |
randomIndex xs = (!!) xs <$> (randomInt $ (length xs) - 1) | |
letters :: Array Char | |
letters = ['A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] | |
randomColor :: forall fx. RandomEff fx String | |
randomColor = | |
fromCharArray <$> randomLetters ['#'] 6 | |
where | |
randomLetters acc n | |
| n <= 0 = pure acc | |
| true = do | |
newLetter <- randomIndex letters | |
oldLetters <- randomLetters acc (n - 1) | |
pure $ oldLetters <> [ '0' `fromMaybe` newLetter ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment