ababup1192
11/6/2016 - 3:38 PM

http://www.softantenna.com/wp/software/5-programming-problems/

import Control.Monad
import Data.Char

problem5 :: [String]
problem5 = do
  ops <- replicateM 8 "+- "
  let expr = filter (not . isSpace) $ interleave ['1'..'9'] ops
  guard $ calc ('+':expr) == 100
  return expr

calc :: String -> Int
calc "" = 0
calc (op:ss) =
  let (num, rest) = span isDigit ss
  in (if op == '+' then 1 else -1) * read num + calc rest

interleave :: [a] -> [a] -> [a]
interleave [] ys = ys
interleave (x:xs) ys = x : interleave ys xs
import Data.List
maxNumOfList :: [Int] -> Int
maxNumOfList = read . maxNum . map show
              where 
                comp a b =  compare (b ++ a) (a ++ b)
                maxNum   = concat . sortBy comp
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
zip' :: [a] -> [b] -> [(a, b)]
zip' x [] = []
zip' [] y = []
zip' (x:xs) (y:ys) = (x, y) : (zip' xs ys)
import Data.IORef
import Control.Monad
import Control.Monad.ST
import Data.STRef
import Data.Traversable
import qualified Data.Vector as V
import Data.Vector ((!))

sumRec :: Num a => [a] -> a
sumRec []     = 0
sumRec (x:xs) = x + sumRec(xs)

-- sumFor :: Num a => [a] -> IO a
-- sumFor xs = do
--    i   <- newIORef 0
--    sum <- newIORef 0
--    sums <- forM [0 .. (length xs)] $ \i -> do
--      sum' <- readIORef sum
--      writeIORef sum $ sum' + xs !! i
--      return sum'
--    return $ last sums



sumFor :: Num a => [a] -> a
sumFor xs = runST $ do
  r <- newSTRef 0
    for 0 (< length xs) (+1) $ \i -> do
      modifySTRef r (+ xs !! i)
  readSTRef r

while :: Monad m => m Bool -> m () -> m ()
  while cond body = do
    b <- cond
    when b $ do
      body
      while cond body

sumWhile :: Num a => [a] -> a
sumWhile xs = runST $ do
  let v = V.fromList xs
  r <- newSTRef 0
  i <- newSTRef 0
  while (readSTRef i >>= return . (< V.length v)) $ do
    i' <- readSTRef i
    modifySTRef r (+ v V.! i')
    modifySTRef i (+1)
  readSTRef r