[Haskell-cafe] Generating random graph
Henning Thielemann
lemming at henning-thielemann.de
Mon Apr 11 09:30:36 CEST 2011
On Mon, 11 Apr 2011, Mitar wrote:
> generateGraph :: Int -> IO (Gr String Double)
> generateGraph graphSize = do
> when (graphSize < 1) $ throwIO $ AssertionFailed $ "Graph size out of bounds " ++ show graphSize
> let ns = map (\n -> (n, show n)) [1..graphSize]
> es <- fmap concat $ forM [1..graphSize] $ \node -> do
> nedges <- randomRIO (0, graphSize)
> others <- fmap (filter (node /=) . nub) $ forM [1..nedges] $ \_ -> randomRIO (1, graphSize)
> gen <- getStdGen
> let weights = randomRs (1, 10) gen
> return $ zip3 (repeat node) others weights
> return $ mkGraph ns es
Just a note on style: This function can perfectly be written without IO.
http://www.haskell.org/haskellwiki/Avoiding_IO#State_monad
More information about the Haskell-Cafe
mailing list