- 1
- 2
instance Show (a -> b)
main = print (*)
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−95
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 (*)
−85
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
−82
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-го элемента списка.
−82
{-# 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.
−79
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
−84
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
−92
-- | 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
−357
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
−91
fac 1 = 1
fac n = fac (n-1) * n
Вычисления факторила advanced-нубами с луркмора(с) на Haskell