Хламидомонада / Говнокод #12976 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
module Main where

import Control.Monad
--import Data.Monoid

data State s a = State (s -> (a, s))

runState :: State s a -> s -> (a, s)
runState (State f) = f

instance Monad (State s) where
			return a = State $ \s -> (a, s)
			ma >>= mf = State $ \s0 -> let (b, s1) = runState ma s0 
				in runState (mf b) s1

type FSM s = State s s 

fsm :: (ev -> s -> s) -> (ev -> FSM s)
fsm transition = \e -> State $ \s -> (s, transition e s)

data PN = NONZ | PONZ | POPZ | NOPZ deriving (Eq,Show)

parse :: Int -> FSM PN
parse = fsm $ trans 
	where trans 1 NONZ= PONZ
	      trans 1 NOPZ= POPZ
	      trans 1 POPZ= NOPZ
	      trans 1 PONZ= NONZ
	      trans 0 POPZ= PONZ
	      trans 0 PONZ= POPZ
	      trans 0 NONZ= NOPZ
	      trans 0 NOPZ= NONZ
	      
conv [] = []
conv ('1':xs) = 1:(conv xs)
conv ('0':xs) = 0:(conv xs)
conv (_:xs) = error "parse error"

main =do
	x <- getLine
	print $ (snd $ runState (mapM parse (conv x)) POPZ) == POPZ
	print $ runState (mapM parse (conv x)) POPZ

Конечный автомат на Haskell

Abbath Abbath, (Updated )

Комментарии (1, +1)

Хламидомонада / Говнокод #12738 Ссылка на оригинал

0

  1. 1
  2. 2
instance Show (a -> b)
main = print (*)

http://liveworkspace.org/code/17QAgf$23
stderr:
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.

Возможно это из-за того, что нет реализации show и я написать вменяемую не смогу. Как заставить Haskell сгенерировать для меня show?

Хочется типа такого:

{-# LANGUAGE OverlappingInstances, FlexibleInstances, UndecidableInstances, StandaloneDeriving, DeriveFunctor #-}
deriving instance Show (a -> b)
main = print (*)

http://liveworkspace.org/code/17QAgf$21
http://www.haskell.org/ghc/docs/6.12.1/html/users_guide/deriving.html
http://www.haskell.org/haskellwiki/GHC/Stand-alone_deriving_declarations

HaskellGovno HaskellGovno, (Updated )

Комментарии (14, +14)

Хламидомонада / Говнокод #12262 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
by :: Int -> [a] -> [[a]]
by _ [] = []
by n xs = take n xs: by n (drop n xs)
 
words2 :: String -> (String, String)
words2 str = conc $ words str where
    conc (x:xs) = (x, concat xs)
 
groupTemplates :: String -> [(String, String)]
groupTemplates xs = map (words2) (lines xs)
 
decodeOne :: String -> [(String, String)] -> String
decodeOne _ [] = ""
decodeOne str (x:xs) | str == fst x = fst x ++ " " ++ snd x ++ "\n"
decodeOne str (_:xs) = decodeOne str xs
 
decode :: [String] -> [(String, String)] -> String
decode bs ts = concat $ map (\b -> decodeOne b ts) bs
 
main = do
    bits      <- readFile "bits.txt"
    templates <- readFile "templates.txt"
 
    writeFile "out.txt" $ decode (by 4 bits) (groupTemplates templates)

http://www.cyberforum.ru/haskell/thread723767.html

Fai Fai, (Updated )

Комментарии (40, +40)

Хламидомонада / Говнокод #12056 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
only :: (Integral nt) => nt -> [Bool]
only n = [ x `mod` n == 0 | x <- [0..] ]

each :: (Integral nt) => nt -> [a] -> [a]
each n xs = [ snd x | x <- filter fst $ zip (only n) xs ]

main = do print $ each 2 [1,2,3,4,5,6,7,8,9]

Haskell. Получение каждого n-го элемента списка.

Fai Fai, (Updated )

Комментарии (104, +104)

Хламидомонада / Говнокод #11976 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
{-# LANGUAGE ExistentialQuantification,
             DeriveDataTypeable,
             PatternSignatures #-}

import Data.Typeable
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Concurrent.Chan

-- Core data types

data Message = forall t . Typeable t => Message t | StopMessage
    deriving Typeable

data Handler = forall t . Typeable t => Handler (t -> IO ())


-- Worker thread

data Worker = Worker (Chan Message) (MVar ())

workerThread :: [Handler] -> Chan Message -> MVar () -> IO ()
workerThread handlers chan finish = loop where
    loop = do
        message <- readChan chan
        case message of
            StopMessage -> putMVar finish ()
            Message val -> do
                foldr (tryHandler val) (putStrLn "Unhandled message") handlers
                loop
    tryHandler val (Handler h) rest = maybe rest h (cast val)

startWorker :: [Handler] -> IO Worker
startWorker handlers = do
    chan <- newChan
    finish <- newEmptyMVar
    forkIO (workerThread handlers chan finish)
    return $ Worker chan finish

send :: Typeable m => Worker -> m -> IO ()
send (Worker chan _) message = do
    writeChan chan $ Message message

stopWorker :: Worker -> IO ()
stopWorker (Worker chan finish) = do
    writeChan chan $ StopMessage
    takeMVar finish


-- Some tests

data Test = Test Bool String deriving Typeable

intHandler :: Int -> IO ()
intHandler val = putStrLn $ "Int: " ++ show (val * 2)

strHandler :: String -> IO ()
strHandler val = putStrLn $ "String: " ++ reverse val

testHandler :: Test -> IO ()
testHandler (Test b s) = putStrLn $ "Test: " ++ show b ++ " " ++ show s

main = do
    w <- startWorker [
        Handler intHandler,
        Handler (\(val::Char) -> putStrLn $ "Char: " ++ show val),
        Handler strHandler,
        Handler testHandler]
    send w (5::Int)
    send w False
    send w 'a'
    send w "foo"
    send w (Test True "bar")
    stopWorker w
    putStrLn "Finished!"

Вот такая вот портянка была написана под влиянием дискуссии с HaskellGovno http://govnokod.ru/11968, и недавней его просьбой рассказать об общении потоков в хаскеле.

Код запускает тред, в который можно передавать различные сообщения (ограничение только одно - тип сообщения должен быть инстансом тайпкласса Typeable). В треде исполняются указанные хендлеры, каждый из которых ловит свой тип сообщений.

P.S. Для неимеющих хаскеля, но желающих посмотреть на работу кода: http://ideone.com/OMVamc.

bormand bormand, (Updated )

Комментарии (43, +43)

Хламидомонада / Говнокод #11510 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
t = 40000 -- количество итераций, чтобы выполнялось примерно 1 миллисекунду
                -- экспериментальным путем определено, что для ideone'вских машин это значение ~40000
 
sleep x = (apply (t*x) id x) `seq`
    ("I've waited ~" ++ show x ++ " milliseconds to tell this: 'pipisiunchik'.")

-- apply применяет ф-цию f к x n раз
apply 0 _ !x = x
apply !n !f !x = apply (n - 1) f (f x)
 
main = putStrLn $ sleep 1000

Спешу представить вам плод моего безделья: чистая ф-ция sleep на Haskell!

Тесты:
1sec - http://ideone.com/sLxRx
3.5sec - http://ideone.com/vn4Fd
10sec - http://ideone.com/U8s36

zim zim, (Updated )

Комментарии (21, +21)

Хламидомонада / Говнокод #11478 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
fibs = 0:1:zipWith (+) fibs (tail fibs)
fib = (fibs !!)
 
main =  let 
                a = [fib 250000..] 
                b = a!!0
                c = 1
        in b `seq` print c

Haskell не может в not used expression elimination. Не используемые константы a и b не убрал из вычисления.
В результате видим пустую трату времени time: 13.15s :
http://ideone.com/41Q8D
И это то ленивом языке, не смотря на то, что эти вычисления не нужны. Можно писать в багтреккер.

P.S.: Когда уже хаскель в подсветку говнокода добавят?

HaskellGovno HaskellGovno, (Updated )

Комментарии (58, +58)

Хламидомонада / Говнокод #10205 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
data (,) a b = (,) a b
    deriving Generic
data (,,) a b c = (,,) a b c
    deriving Generic
data (,,,) a b c d = (,,,) a b c d
    deriving Generic
.......
data (,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p q r s t u v w x y z a_ b_ c_ d_ e_ f_ g_ h_ i_ j_ k_ l_ m_ n_ o_ p_ q_ r_ s_ t_ u_ v_ w_ x_ y_ z_ a__ b__ c__ d__ e__ f__ g__ h__ i__ j__
 = (,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p q r s t u v w x y z a_ b_ c_ d_ e_ f_ g_ h_ i_ j_ k_ l_ m_ n_ o_ p_ q_ r_ s_ t_ u_ v_ w_ x_ y_ z_ a__ b__ c__ d__ e__ f__ g__ h__ i__ j__
    -- deriving Generic
{- Manuel says: Including one more declaration gives a segmentation fault.

Вот такая вот реализация туплов:
http://www.haskell.org/ghc/docs/7.4.1/html/libraries/ghc-prim-0.2.0.0/src/GHC-Tuple.html

bormand bormand, (Updated )

Комментарии (22, +22)

Хламидомонада / Говнокод #9598 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
-- | The unit datatype @()@ has one non-undefined member, the nullary
-- constructor @()@.
data () = () deriving Generic

data (,) a b = (,) a b
. . .
data (,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p q r s t u v w x y z a_ b_ c_ d_ e_ f_ g_ h_ i_ j_ k_ l_ m_ n_ o_ p_ q_ r_ s_ t_ u_ v_ w_ x_ y_ z_ a__ b__ c__ d__ e__ f__ g__ h__ i__ j__
 = (,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p q r s t u v w x y z a_ b_ c_ d_ e_ f_ g_ h_ i_ j_ k_ l_ m_ n_ o_ p_ q_ r_ s_ t_ u_ v_ w_ x_ y_ z_ a__ b__ c__ d__ e__ f__ g__ h__ i__ j__
    -- deriving Generic
{- Manuel says: Including one more declaration gives a segmentation fault.
. . .

*тяжелый вздох*

http://www.haskell.org/ghc/docs/latest/html/libraries/ghc-prim-0.2.0.0/src/GHC-Tuple.html#%28%29

wvxvw wvxvw, (Updated )

Комментарии (65, +65)

Хламидомонада / Говнокод #6765 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
chislo :: String -> Bool
chislo []=True
chislo (x:xs) =if (x=='1') then chislo xs
               else if (x=='2') then chislo xs
                 else if (x=='3') then chislo xs
                   else if (x=='4') then chislo xs
                     else if (x=='5') then chislo xs
                       else if (x=='6') then chislo xs
                         else if (x=='7') then chislo xs
                           else if (x=='8') then chislo xs
                             else if (x=='9') then chislo xs
                               else if (x=='0') then chislo xs
                                 else if (x=='.') then chislo xs
							 else False

haskell

resettik resettik, (Updated )

Комментарии (49, +49)