I saw the following code in my companies codebase and thought to myself "Damn that's a fine line of linq, I'd like to translate that to Haskell to see what it's like in an actual functional language"
static Random random = new Random();
static string RandomString(int length)
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)])
The natural translation to Haskell involves having some sort of
IO (as you need randomness). Since you are essentially trying to perform the action of choosing a character
n times, you want to use
replicateM. Then, for getting a random number in a range, you can use
import Control.Monad (replicateM) import System.Random (randomRIO) randomString :: Int -> IO String randomString n = replicateM n (do r <- randomRIO (0,m); pure (chars !! r)) where chars = ['A'..'Z'] ++ ['0'..'9'] m = length chars
This is somewhat complicated by the fact you want a string of only characters in a certain range. otherwise, you'd have a one liner:
randomString n = replicateM n randomIO.