From markus.boehm at googlemail.com Mon Feb 1 04:37:41 2010 From: markus.boehm at googlemail.com (=?ISO-8859-1?Q?Markus_B=F6hm?=) Date: Mon Feb 1 04:09:19 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <201001312143.12967.daniel.is.fischer@web.de> References: <201001311950.34978.daniel.is.fischer@web.de> <5fdc56d71001311122o18cb30c8p7daedb1d96a45d9c@mail.gmail.com> <201001312143.12967.daniel.is.fischer@web.de> Message-ID: Daniel, Stephen, Felipe thanks for Your answers/advice, which I studied this morning. Helps me a lot on my learning curve. I guess it takes some time to get a feeling for the performance/runtime behaviour of abstractions in Haskell. Just for fun and w/o knowing Lua: I translated my Haskell "loops-while"-version into Lua and ran on LuaJit Beta 2.0.0. Seems to beat our best Haskell version. print("EPS: ") EPS = io.read("*number") pi2 = 1 i = 3 s = false repeat pi1 = pi2 if s then pi2 = pi1 + 1.0/i s = false else pi2 = pi1 - 1.0/i s = true end i = i+2 until EPS > 4.0 * math.abs(pi2-pi1) print("PI mit EPS", EPS," = ",4*pi1," n= ",(i-3)/2) -- Markus On Sun, Jan 31, 2010 at 9:43 PM, Daniel Fischer wrote: > Am Sonntag 31 Januar 2010 20:22:56 schrieb Stephen Tetley: >> On my machine, they diverged at the eighth decimal place - >> >> Leibniz4 3.1415926526069526 >> Leibniz1 3.1415926445727678 > > Ah, that. I thought you were talking about timings. > > There are several things that can lead to differing results here, > > 1) order of summation (I think only my loop had a different order) > 2) due to different tests, it might happen that one algorithm evaluates one > term more than the other > 3) are intermediate results truncated to 64 bits or kept in an 80-bit > register? > > I'm astonished by the size of the difference, though. > > But if you sum from small to large, the results are very accurately the > theoretically expected results, so I think it's 1) together with 3) which > make the difference. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From bugspynet at gmail.com Mon Feb 1 05:34:32 2010 From: bugspynet at gmail.com (Gabi) Date: Mon Feb 1 05:06:08 2010 Subject: [Haskell-beginners] foldl' vs seq Message-ID: <22d241861002010234x6cc548e3m5fd58d88c7dd5c6b@mail.gmail.com> Hi I am trying to understand the behavior of foldl' and seq. Why is the following code is much slower than the foldl' version ? (which is foldl' (+) 0) I thought the the below code is equivalent to foldr' but apparently I was wrong. mySum :: [Integer] -> Integer mySum[] = 0 mySum (x:xs) = seq x (mySum xs + x) From bugspynet at gmail.com Mon Feb 1 06:05:23 2010 From: bugspynet at gmail.com (Gabi) Date: Mon Feb 1 05:37:00 2010 Subject: [Haskell-beginners] foldl' vs seq Message-ID: <22d241861002010305o4c337d8et1978d119daa7041f@mail.gmail.com> Update: I came up with the following somewhat faster function. But still, it is much slower than the original foldl' mySum2 (x:y:xs) = let sum = x + y in seq sum (sum + mySum2 xs) mySum2 (x:[]) = x mySum2 [] = 0 From stephen.tetley at gmail.com Mon Feb 1 06:31:33 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Mon Feb 1 06:03:12 2010 Subject: [Haskell-beginners] foldl' vs seq In-Reply-To: <22d241861002010234x6cc548e3m5fd58d88c7dd5c6b@mail.gmail.com> References: <22d241861002010234x6cc548e3m5fd58d88c7dd5c6b@mail.gmail.com> Message-ID: <5fdc56d71002010331i51c31ac5yb0b1ac6147bea9a5@mail.gmail.com> Hi Gabi The seq is not forcing the strictness that you are expecting. A tail recursive accumulator version is comparable to foldl' (I'm not sure which other pieces out of the bag of strictness tricks deepseq, etc would get the same results without the accumulator). Best wishes Stephen All versions compiled with -O2... module Main where mySum :: [Integer] -> Integer mySum xs0 = step 0 xs0 where step a [] = a step a (x:xs) = let a' = a+x in a' `seq` step a' xs main = do putStrLn "mySum tail-rec:" putStrLn $ "mySum [1..10^6]:" ++ show (mySum [1..10^6]) ----------------- $ ./MySumTR.exe +RTS -sstderr -RTS d:\coding\haskell\cafe\MySumTR.exe +RTS -sstderr mySum tail-rec: mySum [1..10^6]:500000500000 100,439,096 bytes allocated in the heap 16,572 bytes copied during GC 3,276 bytes maximum residency (1 sample(s)) 11,944 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 192 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.02s ( 0.00s elapsed) MUT time 0.33s ( 0.33s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.34s ( 0.33s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate 292,186,461 bytes per MUT second Productivity 95.5% of total user, 100.0% of total elapsed ----------------------------- $ ./SeqFoldl.exe +RTS -sstderr -RTS d:\coding\haskell\cafe\SeqFoldl.exe +RTS -sstderr sum (foldl'): sum [1..10^6]:500000500000 100,438,952 bytes allocated in the heap 16,572 bytes copied during GC 3,276 bytes maximum residency (1 sample(s)) 11,944 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 192 collections, 0 parallel, 0.03s, 0.03s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.02s ( 0.00s elapsed) MUT time 0.30s ( 0.30s elapsed) GC time 0.03s ( 0.03s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.34s ( 0.33s elapsed) %GC time 9.1% (9.5% elapsed) Alloc rate 321,404,646 bytes per MUT second Productivity 86.4% of total user, 90.5% of total elapsed From bugspynet at gmail.com Mon Feb 1 06:54:31 2010 From: bugspynet at gmail.com (Gabi) Date: Mon Feb 1 06:50:12 2010 Subject: [Haskell-beginners] foldl' vs seq Message-ID: <22d241861002010354y2a34eae5u719050c7c6502a0f@mail.gmail.com> Hi Stephen, Thanks for the answer. Now I got confused :) 1. What is seq used for if it doesn't force strictness ? 2. Why the accumulator is important ? In other words why the following is much slower ? Isn't it RT too ? slowSum :: [Integer] -> Integer slowSum[] = 0 slowSum (x:xs) = x `seq` x + slowSum xs From jao at gnu.org Mon Feb 1 06:48:02 2010 From: jao at gnu.org (Jose A. Ortega Ruiz) Date: Mon Feb 1 06:51:45 2010 Subject: [Haskell-beginners] problem with hsc2hs Message-ID: <87pr4p41ot.fsf@newton.homeunix.net> Hi, I'm trying to writing a simple C binding for statfs(2). Simplifying, writing an hsc file that contains the following snippet: #include data CStatfs foreign import ccall unsafe "sys/vfs.h statfs" c_statfs :: CString -> Ptr CStatfs -> IO CInt getFileSystemStats :: String -> IO CLong getFileSystemStats path = allocaBytes (#size struct statfs) $ \vfs -> useAsCString (pack path) $ \cpath -> do res <- c_statfs cpath vfs case res of -1 -> return 0 _ -> do bsize <- (#peek struct statfs, f_bsize) vfs bcount <- (#peek struct statfs, f_blocks) vfs bfree <- (#peek struct statfs, f_bfree) vfs bavail <- (#peek struct statfs, f_bavail) vfs -- Just for demonstration: the original code creates a data structure return $ bsize + bcount + bavail + bfree gives rise, when using hsc2hs, to this translation: getFileSystemStats path = allocaBytes ((84)) $ \vfs -> useAsCString (pack path) $ \cpath -> do res <- c_statfs cpath vfs case res of -1 -> return 0 _ -> do bsize <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) vfs bcount <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) vfs bfree <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) vfs bavail <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) vfs return $ bsize + bcount + bavail + bfree (where i have deleted LINE directives). The problem is that the size and some of the offsets of the C struct statfs computed by hsc2c are wrong: i'm in a 32bit linux system, and i've checked, using a C program, that sizeof(struct statfs) is 64 (hsc2 is giving 84 -- although perhaps Haskell needs additional space for housekeeping?), and that the offsets of f_bfree and f_bavail are, respectively, 12 and 16 (not 16 and 24). Also, i know that 12 and 16 are the right values because putting them by hand gives me the correct statfs values. (This is ghc 6.10.4 on a debian/sid system) What am i doing wrong? TIA! jao From stephen.tetley at gmail.com Mon Feb 1 08:15:16 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Mon Feb 1 07:46:52 2010 Subject: [Haskell-beginners] foldl' vs seq In-Reply-To: <22d241861002010354y2a34eae5u719050c7c6502a0f@mail.gmail.com> References: <22d241861002010354y2a34eae5u719050c7c6502a0f@mail.gmail.com> Message-ID: <5fdc56d71002010515v39a6d547x76a7dd16163bb66f@mail.gmail.com> I On 1 February 2010 11:54, Gabi wrote: > Hi Stephen, > Thanks for the answer. Now I got confused :) > > 1. What is seq used for if it doesn't force strictness ? > 2. Why the accumulator is important ? In other words why the following > is much slower ? Isn't it RT too ? > > slowSum :: [Integer] -> Integer > slowSum[] = 0 > slowSum (x:xs) = x `seq` x + slowSum xs Hi Gabi It seems to be classified as 'almost tail recursion', see here: http://www.haskell.org/haskellwiki/Performance/Accumulating_parameter In slowSum although x gets 'forced' it still has to be added to the result of the recursive call [ slowSum xs ], so there isn't much that can actually be done with it at each recursive step until you get an answer back (what it actually does is build up the notorious [x + ..] thunks). Best wishes Stephen From daniel.is.fischer at web.de Mon Feb 1 08:16:59 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 1 07:50:26 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: <201001312143.12967.daniel.is.fischer@web.de> Message-ID: <201002011416.59291.daniel.is.fischer@web.de> Am Montag 01 Februar 2010 10:37:41 schrieb Markus B?hm: > Daniel, Stephen, Felipe thanks for Your answers/advice, which I > studied this morning. Helps me a lot on my learning curve. I guess it > takes some time to get a feeling for the performance/runtime behaviour > of abstractions in Haskell. > > Just for fun and w/o knowing Lua: I translated my Haskell > "loops-while"-version into Lua That's not quite a translation of the loop you posted. Not really important, though, small difference. > and ran on LuaJit Beta 2.0.0. Seems to > beat our best Haskell version. So LuaJit Beta 2.0.0 beats gcc -O3 on such a simple loop? I'm not going to install Lua to test, but if that's really the case, I'm sure the folks at gnu.org would like to hear about it. Or don't you consider -fvia-C compiled loops to be true Haskell versions? > > print("EPS: ") > EPS = io.read("*number") > pi2 = 1 > i = 3 > s = false > repeat > pi1 = pi2 > if s then > pi2 = pi1 + 1.0/i > s = false > else > pi2 = pi1 - 1.0/i > s = true > end > i = i+2 > > until EPS > 4.0 * math.abs(pi2-pi1) > > print("PI mit EPS", EPS," = ",4*pi1," n= ",(i-3)/2) > > > -- Markus From markus.boehm at googlemail.com Mon Feb 1 08:31:40 2010 From: markus.boehm at googlemail.com (=?ISO-8859-1?Q?Markus_B=F6hm?=) Date: Mon Feb 1 08:03:17 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <201002011416.59291.daniel.is.fischer@web.de> References: <201001312143.12967.daniel.is.fischer@web.de> <201002011416.59291.daniel.is.fischer@web.de> Message-ID: Daniel, with LuaJIT it needs 1.45 sec cpu-time on my machine with attached variant. I compiled all our Haskell variants with ghc --make -O2. I don't know about -fvia-C, have to find out. I hope I didn't distract You with my Lua variant. In any case thank You very much for your advice. Markus. print("EPS: ") EPS = io.read("*number") local x = os.clock() pi2 = 1 i = 3 s = false repeat pi1 = pi2 if s then pi2 = pi1 + 1.0/i s = false else pi2 = pi1 - 1.0/i s = true end i = i+2 until EPS > 4.0 * math.abs(pi2-pi1) print("PI mit EPS", EPS," = ",4*pi1," n= ",(i-3)/2) print(string.format("elapsed time: %.2f\n", os.clock() -x)) -- Markus On Mon, Feb 1, 2010 at 2:16 PM, Daniel Fischer wrote: > Am Montag 01 Februar 2010 10:37:41 schrieb Markus B?hm: >> Daniel, Stephen, Felipe thanks for Your answers/advice, which I >> studied this morning. Helps me a lot on my learning curve. I guess it >> takes some time to get a feeling for the performance/runtime behaviour >> of abstractions in Haskell. >> >> Just for fun and w/o knowing Lua: I translated my Haskell >> "loops-while"-version into Lua > > That's not quite a translation of the loop you posted. Not really > important, though, small difference. > >> and ran on LuaJit Beta 2.0.0. Seems to >> beat our best Haskell version. > > So LuaJit Beta 2.0.0 beats gcc -O3 on such a simple loop? > I'm not going to install Lua to test, but if that's really the case, I'm > sure the folks at gnu.org would like to hear about it. > Or don't you consider -fvia-C compiled loops to be true Haskell versions? > >> >> print("EPS: ") >> EPS = io.read("*number") >> pi2 = 1 >> i = 3 >> s = false >> repeat >> ? ? pi1 = pi2 >> ? ? if s then >> ? ? ? ? pi2 = pi1 + 1.0/i >> ? ? ? ? s = false >> ? ? else >> ? ? ? ? pi2 = pi1 - 1.0/i >> ? ? ? ? s = true >> ? ? end >> ? ? i = i+2 >> >> until EPS > 4.0 * math.abs(pi2-pi1) >> >> print("PI mit EPS", EPS," = ",4*pi1," n= ",(i-3)/2) >> >> >> -- Markus > From stephen.tetley at gmail.com Mon Feb 1 08:32:17 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Mon Feb 1 08:03:52 2010 Subject: [Haskell-beginners] foldl' vs seq In-Reply-To: <5fdc56d71002010515v39a6d547x76a7dd16163bb66f@mail.gmail.com> References: <22d241861002010354y2a34eae5u719050c7c6502a0f@mail.gmail.com> <5fdc56d71002010515v39a6d547x76a7dd16163bb66f@mail.gmail.com> Message-ID: <5fdc56d71002010532p7a41dbf8qef4e0fa786f57cc4@mail.gmail.com> Hi Gabi Furthermore, a bit of rewriting might make a better explanation. Ignoring the seq, the right-hand side is: fn (x:xs) = x + fn xs Although the recursive step is the rightmost part, (fn xs) must return back to (x + ...) to perform the summing. If the arguments are swapped, the function is the same but the recursive step is obviously not in the tail position: fn (x:xs) = (fn xs) + x Best wishes Stephen From daniel.is.fischer at web.de Mon Feb 1 08:52:41 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 1 08:26:06 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: <201002011416.59291.daniel.is.fischer@web.de> Message-ID: <201002011452.41904.daniel.is.fischer@web.de> Am Montag 01 Februar 2010 14:31:40 schrieb Markus B?hm: > Daniel, with LuaJIT it needs 1.45 sec cpu-time on my machine with > attached variant. That's pretty fast. > I compiled all our Haskell variants with ghc --make -O2. Well, GHC isn't as good at loop-optimising as gcc is. Depending on the loop, the via-C compiled binaries are between 1.4 and 2.3 times faster than the NCG compiled. > I don't know about -fvia-C, have to find out. I hope I didn't > distract You with my Lua variant. No sweat. > In any case thank You very much for > your advice. Markus. > You're welcome. Can you try the below with ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop --make Whatever.hs and run with echo '0.00000001' | time ./luaLoop ? It's a fairly direct translation of the Lua code, and it runs here more or less equally fast as (gcc compiled) C-loops. ================================= module Main (main) where main :: IO () main = do putStrLn "EPS:" eps <- readLn :: IO Double print $ 4*calcPi eps calcPi :: Double -> Double calcPi eps = go False 1 3 where go bl p1 i | 4*abs(p2-p1) < eps = p1 | otherwise = go (not bl) p2 (i+2) where p2 | bl = p1+1/i | otherwise = p1-1/i ================================== From markus.boehm at googlemail.com Mon Feb 1 09:08:58 2010 From: markus.boehm at googlemail.com (=?ISO-8859-1?Q?Markus_B=F6hm?=) Date: Mon Feb 1 08:40:34 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <201002011452.41904.daniel.is.fischer@web.de> References: <201002011416.59291.daniel.is.fischer@web.de> <201002011452.41904.daniel.is.fischer@web.de> Message-ID: Daniel, I use GHC 6.12.1 and Windows XP. The time command doesn't seem to work. It says in German: specified time can't be read. Give a new time. -- Markus On Mon, Feb 1, 2010 at 2:52 PM, Daniel Fischer wrote: > Am Montag 01 Februar 2010 14:31:40 schrieb Markus B?hm: >> Daniel, with LuaJIT it needs 1.45 sec cpu-time on my machine with >> attached variant. > > That's pretty fast. > >> I compiled all our Haskell variants with ghc --make -O2. > > Well, GHC isn't as good at loop-optimising as gcc is. Depending on the > loop, the via-C compiled binaries are between 1.4 and 2.3 times faster than > the NCG compiled. > >> I don't know about -fvia-C, have to find out. I hope I didn't >> distract You with my Lua variant. > > No sweat. > >> In any case thank You very much for >> your advice. Markus. >> > > You're welcome. > > Can you try the below with > > ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop --make Whatever.hs > > and run with > > echo '0.00000001' | time ./luaLoop > > ? > It's a fairly direct translation of the Lua code, and it runs here more or > less equally fast as (gcc compiled) C-loops. > > ================================= > module Main (main) where > > main :: IO () > main = do > ? ?putStrLn "EPS:" > ? ?eps <- readLn :: IO Double > ? ?print $ 4*calcPi eps > > calcPi :: Double -> Double > calcPi eps = go False 1 3 > ? ? ?where > ? ? ? ?go bl p1 i > ? ? ? ? ? ?| 4*abs(p2-p1) < eps ? ?= p1 > ? ? ? ? ? ?| otherwise ? ? ? ? ? ? = go (not bl) p2 (i+2) > ? ? ? ? ? ? ?where > ? ? ? ? ? ? ? ?p2 ?| bl ? ? ? ?= p1+1/i > ? ? ? ? ? ? ? ? ? ?| otherwise = p1-1/i > > ================================== > > From markus.boehm at googlemail.com Mon Feb 1 09:22:45 2010 From: markus.boehm at googlemail.com (=?ISO-8859-1?Q?Markus_B=F6hm?=) Date: Mon Feb 1 08:54:20 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: <201002011416.59291.daniel.is.fischer@web.de> <201002011452.41904.daniel.is.fischer@web.de> Message-ID: Daniel, here another feedback: F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop --make p 085-pi_lualoop.hs [1 of 1] Compiling Main ( p085-pi_lualoop.hs, p085-pi_lualoop.o ) Linking luaLoop.exe ... F:\MeineUebungen>echo '0.00000001' | time ./luaLoop Eingegebene Zeit kann nicht ?bernommen werden. Geben Sie die neue Zeit ein: F:\MeineUebungen>luaLoop +RTS -sstderr -RTS luaLoop +RTS -sstderr EPS: 0.00000001 3.1415926485894725 61,428 bytes allocated in the heap 1,316 bytes copied during GC 4,564 bytes maximum residency (1 sample(s)) 11,820 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.02s ( 0.00s elapsed) MUT time 8.06s ( 16.83s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 8.08s ( 16.83s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate 7,604 bytes per MUT second Productivity 99.8% of total user, 47.9% of total elapsed -- Markus On Mon, Feb 1, 2010 at 3:08 PM, Markus B?hm wrote: > Daniel, I use GHC 6.12.1 and Windows XP. The time command doesn't seem > to work. It says in German: specified time can't be read. Give a new > time. > > -- Markus > > > > > On Mon, Feb 1, 2010 at 2:52 PM, Daniel Fischer wrote: >> Am Montag 01 Februar 2010 14:31:40 schrieb Markus B?hm: >>> Daniel, with LuaJIT it needs 1.45 sec cpu-time on my machine with >>> attached variant. >> >> That's pretty fast. >> >>> I compiled all our Haskell variants with ghc --make -O2. >> >> Well, GHC isn't as good at loop-optimising as gcc is. Depending on the >> loop, the via-C compiled binaries are between 1.4 and 2.3 times faster than >> the NCG compiled. >> >>> I don't know about -fvia-C, have to find out. I hope I didn't >>> distract You with my Lua variant. >> >> No sweat. >> >>> In any case thank You very much for >>> your advice. Markus. >>> >> >> You're welcome. >> >> Can you try the below with >> >> ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop --make Whatever.hs >> >> and run with >> >> echo '0.00000001' | time ./luaLoop >> >> ? >> It's a fairly direct translation of the Lua code, and it runs here more or >> less equally fast as (gcc compiled) C-loops. >> >> ================================= >> module Main (main) where >> >> main :: IO () >> main = do >> ? ?putStrLn "EPS:" >> ? ?eps <- readLn :: IO Double >> ? ?print $ 4*calcPi eps >> >> calcPi :: Double -> Double >> calcPi eps = go False 1 3 >> ? ? ?where >> ? ? ? ?go bl p1 i >> ? ? ? ? ? ?| 4*abs(p2-p1) < eps ? ?= p1 >> ? ? ? ? ? ?| otherwise ? ? ? ? ? ? = go (not bl) p2 (i+2) >> ? ? ? ? ? ? ?where >> ? ? ? ? ? ? ? ?p2 ?| bl ? ? ? ?= p1+1/i >> ? ? ? ? ? ? ? ? ? ?| otherwise = p1-1/i >> >> ================================== >> >> > From daniel.is.fischer at web.de Mon Feb 1 09:40:52 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 1 09:14:21 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: Message-ID: <201002011540.53154.daniel.is.fischer@web.de> Am Montag 01 Februar 2010 15:22:45 schrieb Markus B?hm: > Daniel, I use GHC 6.12.1 and Windows XP. *sigh* Have you a CygWin installed? It should run as given from a CygWin shell, I believe. > The time command doesn't seem > to work. It says in German: specified time can't be read. Give a new > time. Replace "time" with however you get the CPU time used by a process on Windows. But I think Windows doesn't allow piping, and I'm not sure whether it has echo, so see below. > Daniel, here another feedback: > > F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop > --make p 085-pi_lualoop.hs > [1 of 1] Compiling Main ( p085-pi_lualoop.hs, > p085-pi_lualoop.o ) Linking luaLoop.exe ... > > F:\MeineUebungen>echo '0.00000001' | time ./luaLoop > Eingegebene Zeit kann nicht ?bernommen werden. > Geben Sie die neue Zeit ein: > > F:\MeineUebungen>luaLoop +RTS -sstderr -RTS > luaLoop +RTS -sstderr > EPS: > 0.00000001 > 3.1415926485894725 > 61,428 bytes allocated in the heap > 1,316 bytes copied during GC > 4,564 bytes maximum residency (1 sample(s)) > 11,820 bytes maximum slop > 1 MB total memory in use (0 MB lost due to fragmentation) > > Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s > elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s > elapsed > > INIT time 0.02s ( 0.00s elapsed) > MUT time 8.06s ( 16.83s elapsed) > GC time 0.00s ( 0.00s elapsed) > EXIT time 0.00s ( 0.00s elapsed) > Total time 8.08s ( 16.83s elapsed) > > %GC time 0.0% (0.0% elapsed) > > Alloc rate 7,604 bytes per MUT second > > Productivity 99.8% of total user, 47.9% of total elapsed What????? Please try the following: 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it as a command line argument) 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop -- make Source.hs 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs 4) cloop +RTS -sstderr 5) nloop +RTS -sstderr > > -- Markus > From markus.boehm at googlemail.com Mon Feb 1 09:59:59 2010 From: markus.boehm at googlemail.com (=?ISO-8859-1?Q?Markus_B=F6hm?=) Date: Mon Feb 1 09:31:34 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <201002011540.53154.daniel.is.fischer@web.de> References: <201002011540.53154.daniel.is.fischer@web.de> Message-ID: 1. I used Your lualoop file with content: module Main (main) where main :: IO () main = do --putStrLn "EPS:" -- eps <- readLn :: IO Double print $ 4*calcPi 0.00000001 calcPi :: Double -> Double calcPi eps = go False 1 3 where go bl p1 i | 4*abs(p2-p1) < eps = p1 | otherwise = go (not bl) p2 (i+2) where p2 | bl = p1+1/i | otherwise = p1-1/i 2. F:\MeineUebungen>ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o c loop --make p085-pi_lualoop.hs [1 of 1] Compiling Main ( p085-pi_lualoop.hs, p085-pi_lualoop.o ) Linking cloop.exe ... F:\MeineUebungen>ghc -O2 -fforce-recomp -o nloop --make p085-pi_lualoop.hs [1 of 1] Compiling Main ( p085-pi_lualoop.hs, p085-pi_lualoop.o ) Linking nloop.exe ... F:\MeineUebungen>cloop +RTS -sstderr cloop +RTS -sstderr 3.1415926485894725 20,860 bytes allocated in the heap 892 bytes copied during GC 3,068 bytes maximum residency (1 sample(s)) 13,316 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.02s ( 0.02s elapsed) MUT time 7.39s ( 7.27s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 7.41s ( 7.28s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate 2,816 bytes per MUT second Productivity 99.8% of total user, 101.5% of total elapsed F:\MeineUebungen>nloop +RTS -sstderr nloop +RTS -sstderr 3.1415926485894725 20,860 bytes allocated in the heap 892 bytes copied during GC 3,068 bytes maximum residency (1 sample(s)) 13,316 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.02s ( 0.00s elapsed) MUT time 4.77s ( 4.81s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 4.78s ( 4.81s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate 4,362 bytes per MUT second Productivity 99.7% of total user, 99.0% of total elapsed -- Markus On Mon, Feb 1, 2010 at 3:40 PM, Daniel Fischer wrote: > Am Montag 01 Februar 2010 15:22:45 schrieb Markus B?hm: > >> Daniel, I use GHC 6.12.1 and Windows XP. > > *sigh* > > Have you a CygWin installed? It should run as given from a CygWin shell, I > believe. > >> The time command doesn't seem >> to work. It says in German: specified time can't be read. Give a new >> time. > > Replace "time" with however you get the CPU time used by a process on > Windows. > But I think Windows doesn't allow piping, and I'm not sure whether it has > echo, so see below. > >> Daniel, here another feedback: >> >> F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop >> --make p 085-pi_lualoop.hs >> [1 of 1] Compiling Main ? ? ? ? ? ? ( p085-pi_lualoop.hs, >> p085-pi_lualoop.o ) Linking luaLoop.exe ... >> >> F:\MeineUebungen>echo '0.00000001' | time ./luaLoop >> Eingegebene Zeit kann nicht ?bernommen werden. >> Geben Sie die neue Zeit ein: >> >> F:\MeineUebungen>luaLoop +RTS -sstderr -RTS >> luaLoop +RTS -sstderr >> EPS: >> 0.00000001 >> 3.1415926485894725 >> ? ? ? ? ? 61,428 bytes allocated in the heap >> ? ? ? ? ? ?1,316 bytes copied during GC >> ? ? ? ? ? ?4,564 bytes maximum residency (1 sample(s)) >> ? ? ? ? ? 11,820 bytes maximum slop >> ? ? ? ? ? ? ? ?1 MB total memory in use (0 MB lost due to fragmentation) >> >> ? Generation 0: ? ? 0 collections, ? ? 0 parallel, ?0.00s, ?0.00s >> elapsed Generation 1: ? ? 1 collections, ? ? 0 parallel, ?0.00s, ?0.00s >> elapsed >> >> ? INIT ?time ? ?0.02s ?( ?0.00s elapsed) >> ? MUT ? time ? ?8.06s ?( 16.83s elapsed) >> ? GC ? ?time ? ?0.00s ?( ?0.00s elapsed) >> ? EXIT ?time ? ?0.00s ?( ?0.00s elapsed) >> ? Total time ? ?8.08s ?( 16.83s elapsed) >> >> ? %GC time ? ? ? 0.0% ?(0.0% elapsed) >> >> ? Alloc rate ? ?7,604 bytes per MUT second >> >> ? Productivity ?99.8% of total user, 47.9% of total elapsed > > What????? > > Please try the following: > > 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it as > a command line argument) > 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop -- > make Source.hs > 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs > 4) cloop +RTS -sstderr > 5) nloop +RTS -sstderr > >> >> -- Markus >> > From daniel.is.fischer at web.de Mon Feb 1 11:10:46 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 1 10:44:22 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: <201002011540.53154.daniel.is.fischer@web.de> Message-ID: <201002011710.46352.daniel.is.fischer@web.de> Am Montag 01 Februar 2010 15:59:59 schrieb Markus B?hm: > 1. I used Your lualoop file with content: > module Main (main) where > > main :: IO () > main = do > --putStrLn "EPS:" > -- eps <- readLn :: IO Double > print $ 4*calcPi 0.00000001 > > calcPi :: Double -> Double > calcPi eps = go False 1 3 > where > go bl p1 i > > | 4*abs(p2-p1) < eps = p1 > | otherwise = go (not bl) p2 (i+2) > > where > p2 | bl = p1+1/i > > | otherwise = p1-1/i > Oops, I've screwed up my timings earlier, that variant doesn't quite give optimal speed (3.65s via-C vs.3.02s for the other loops, but the NCG code of that takes a whopping 12.13s here vs. 4.x - 6.y s for the other loops), what I had measured was ==================================== calcPi :: Double -> Double calcPi eps = go False 1 3 ? ? ? where go True p1 i | 4*(p2-p1) < eps = p1 | otherwise = go False p2 (i+2) where p2 = p1+1/i go False p1 i | 4*(p1-p2) < eps = p1 | otherwise = go True p2 (i+2) where p2 = p1-1/i ==================================== (which gives 3.03s via C and 6.91s with the NCG). Mind trying that, too? Nevertheless, the results are seriously disturbing. The previous code runs more than 2.5 times as fast on your computer than on mine when compiled with the NCG and twice as fast on my computer than on yours when compiled via C. I don't know what to make of it. > 2. > F:\MeineUebungen>ghc -O2 -fforce-recomp -fexcess-precision -fvia-C > -optc-O3 -o c loop --make p085-pi_lualoop.hs > [1 of 1] Compiling Main ( p085-pi_lualoop.hs, > p085-pi_lualoop.o ) Linking cloop.exe ... > > > F:\MeineUebungen>ghc -O2 -fforce-recomp -o nloop --make > p085-pi_lualoop.hs [1 of 1] Compiling Main ( > p085-pi_lualoop.hs, p085-pi_lualoop.o ) Linking nloop.exe ... > > F:\MeineUebungen>cloop +RTS -sstderr > cloop +RTS -sstderr > 3.1415926485894725 > 20,860 bytes allocated in the heap > 892 bytes copied during GC > 3,068 bytes maximum residency (1 sample(s)) > 13,316 bytes maximum slop > 1 MB total memory in use (0 MB lost due to fragmentation) > > Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s > elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s > elapsed > > INIT time 0.02s ( 0.02s elapsed) > MUT time 7.39s ( 7.27s elapsed) > GC time 0.00s ( 0.00s elapsed) > EXIT time 0.00s ( 0.00s elapsed) > Total time 7.41s ( 7.28s elapsed) > > %GC time 0.0% (0.0% elapsed) > > Alloc rate 2,816 bytes per MUT second > > Productivity 99.8% of total user, 101.5% of total elapsed > > > F:\MeineUebungen>nloop +RTS -sstderr > nloop +RTS -sstderr > 3.1415926485894725 > 20,860 bytes allocated in the heap > 892 bytes copied during GC > 3,068 bytes maximum residency (1 sample(s)) > 13,316 bytes maximum slop > 1 MB total memory in use (0 MB lost due to fragmentation) > > Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s > elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s > elapsed > > INIT time 0.02s ( 0.00s elapsed) > MUT time 4.77s ( 4.81s elapsed) > GC time 0.00s ( 0.00s elapsed) > EXIT time 0.00s ( 0.00s elapsed) > Total time 4.78s ( 4.81s elapsed) > > %GC time 0.0% (0.0% elapsed) > > Alloc rate 4,362 bytes per MUT second > > Productivity 99.7% of total user, 99.0% of total elapsed > > > -- Markus From perry2of5 at yahoo.com Mon Feb 1 14:15:25 2010 From: perry2of5 at yahoo.com (Tim Perry) Date: Mon Feb 1 14:19:18 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <201002011540.53154.daniel.is.fischer@web.de> References: <201002011540.53154.daniel.is.fischer@web.de> Message-ID: <967918.68772.qm@web54304.mail.re2.yahoo.com> CygWin would be a good option. Here are some other ideas: There is a timeit.exe utility in the Windows Server downloads which is supposed to be similar to unix's time command. Try the links here http://channel9.msdn.com/forums/Coffeehouse/258979-Windows-equivalent-of-UnixLinux-time-command/ Windows does support piping. It is similar to bash with 2>&1 to redirect stderr to stdout and stuff. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true The new windows shell is almost a real shell. Almost. If you don't have that, then this port of unix utilities makes an XP box tolerable. http://unxutils.sourceforge.net/ Hope that helps. --Tim ----- Original Message ---- From: Daniel Fischer To: Markus B?hm Cc: beginners@haskell.org Sent: Mon, February 1, 2010 6:40:52 AM Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell Am Montag 01 Februar 2010 15:22:45 schrieb Markus B?hm: > Daniel, I use GHC 6.12.1 and Windows XP. *sigh* Have you a CygWin installed? It should run as given from a CygWin shell, I believe. > The time command doesn't seem > to work. It says in German: specified time can't be read. Give a new > time. Replace "time" with however you get the CPU time used by a process on Windows. But I think Windows doesn't allow piping, and I'm not sure whether it has echo, so see below. > Daniel, here another feedback: > > F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop > --make p 085-pi_lualoop.hs > [1 of 1] Compiling Main ( p085-pi_lualoop.hs, > p085-pi_lualoop.o ) Linking luaLoop.exe ... > > F:\MeineUebungen>echo '0.00000001' | time ./luaLoop > Eingegebene Zeit kann nicht ?bernommen werden. > Geben Sie die neue Zeit ein: > > F:\MeineUebungen>luaLoop +RTS -sstderr -RTS > luaLoop +RTS -sstderr > EPS: > 0.00000001 > 3.1415926485894725 > 61,428 bytes allocated in the heap > 1,316 bytes copied during GC > 4,564 bytes maximum residency (1 sample(s)) > 11,820 bytes maximum slop > 1 MB total memory in use (0 MB lost due to fragmentation) > > Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s > elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s > elapsed > > INIT time 0.02s ( 0.00s elapsed) > MUT time 8.06s ( 16.83s elapsed) > GC time 0.00s ( 0.00s elapsed) > EXIT time 0.00s ( 0.00s elapsed) > Total time 8.08s ( 16.83s elapsed) > > %GC time 0.0% (0.0% elapsed) > > Alloc rate 7,604 bytes per MUT second > > Productivity 99.8% of total user, 47.9% of total elapsed What????? Please try the following: 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it as a command line argument) 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop -- make Source.hs 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs 4) cloop +RTS -sstderr 5) nloop +RTS -sstderr > > -- Markus > _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners From kane96 at gmx.de Mon Feb 1 15:20:48 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Feb 1 14:52:29 2010 Subject: [Haskell-beginners] foldr for Nats In-Reply-To: <5fdc56d71001260305h3a55380bv78e2732d68976708@mail.gmail.com> References: <20100126105245.288430@gmx.net> <5fdc56d71001260305h3a55380bv78e2732d68976708@mail.gmail.com> Message-ID: <20100201202048.41080@gmx.net> yeahh, I know that it is similar, but don't know how to start implementing it. -------- Original-Nachricht -------- > Datum: Tue, 26 Jan 2010 11:05:20 +0000 > Von: Stephen Tetley > An: > CC: Beginners@haskell.org > Betreff: Re: [Haskell-beginners] foldr for Nats > Hi > > One hint is that your data type for natural numbers is remarkably like > the data type for lists... > > data List a = [] | a : List a > > The difference is that List has an element of type 'a' at the non-zero > cases. > > Best wishes > > Stephen > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From markwvh at gmail.com Mon Feb 1 15:21:12 2010 From: markwvh at gmail.com (Mark Wong-VanHaren) Date: Mon Feb 1 14:52:47 2010 Subject: [Haskell-beginners] Problems installing TagSoup.Parsec Message-ID: Hi, folks- I'm a Haskell newbie. There's a very real chance my question has a simple answer. I wish to use the library Text.HTML.TagSoup.Parsec ( http://hackage.haskell.org/package/tagsoup-parsec), which looks very cool. When I attempt to install it, I get this error: # cabal install tagsoup-parsec Resolving dependencies... Configuring tagsoup-parsec-0.0.6... Preprocessing library tagsoup-parsec-0.0.6... Building tagsoup-parsec-0.0.6... [1 of 1] Compiling Text.HTML.TagSoup.Parsec ( Text/HTML/TagSoup/Parsec.hs, dist/build/Text/HTML/TagSoup/Parsec.o ) Text/HTML/TagSoup/Parsec.hs:37:5: `Tag' is not applied to enough type arguments Expected kind `*', but `Tag' has kind `* -> *' In the type synonym declaration for `WholeTag' cabal: Error: some packages failed to install: tagsoup-parsec-0.0.6 failed during the building phase. The exception was: exit: ExitFailure 1 It would seem to be a type mismatch between TagSoup.Parsec and the base TagSoup (on which it depends). Suspecting that the version-number dependency information might be incorrect, I tried uninstalling TagSoup and reinstalling an older version. This didn't help. Can anyone steer me in the right direction? Thanks! -Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100201/bf84eb3e/attachment-0001.html From daniel.is.fischer at web.de Mon Feb 1 15:42:14 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 1 15:15:58 2010 Subject: [Haskell-beginners] Problems installing TagSoup.Parsec In-Reply-To: References: Message-ID: <201002012142.14394.daniel.is.fischer@web.de> Am Montag 01 Februar 2010 21:21:12 schrieb Mark Wong-VanHaren: > Hi, folks- > > I'm a Haskell newbie. There's a very real chance my question has a > simple answer. Yes and no. The problem is that the build-depends field of tagsoup- parsec.cabal doesn't specify an upper bound on the version of tagsoup to use. Thus cabal tries to build it with the latest and greates tagsoup, 0.8. Neill Mitchell changed the tagsoup API, bad .cabal files break. Fix: unpack tagsoup-parsec-0.0.6, open the .cabal file, change Library Build-Depends: base<5, tagsoup, parsec<3 to Library Build-Depends: base<5, tagsoup < 0.7, parsec<3 $ cd tagsoup-parsec-0.0.6 $ cabal install email maintainer of tagsoup-parsec to fix it (adapt to new tagsoup API). > > I wish to use the library Text.HTML.TagSoup.Parsec ( > http://hackage.haskell.org/package/tagsoup-parsec), which looks very > cool. > > When I attempt to install it, I get this error: > > # cabal install tagsoup-parsec > Resolving dependencies... > Configuring tagsoup-parsec-0.0.6... > Preprocessing library tagsoup-parsec-0.0.6... > Building tagsoup-parsec-0.0.6... > [1 of 1] Compiling Text.HTML.TagSoup.Parsec ( > Text/HTML/TagSoup/Parsec.hs, dist/build/Text/HTML/TagSoup/Parsec.o ) > > Text/HTML/TagSoup/Parsec.hs:37:5: > `Tag' is not applied to enough type arguments > Expected kind `*', but `Tag' has kind `* -> *' > In the type synonym declaration for `WholeTag' > cabal: Error: some packages failed to install: > tagsoup-parsec-0.0.6 failed during the building phase. The exception > was: exit: ExitFailure 1 > > > It would seem to be a type mismatch between TagSoup.Parsec and the base > TagSoup (on which it depends). > > Suspecting that the version-number dependency information might be > incorrect, I tried uninstalling TagSoup and reinstalling an older > version. This didn't help. > > Can anyone steer me in the right direction? > > Thanks! > -Mark From stephen.tetley at gmail.com Mon Feb 1 16:56:14 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Mon Feb 1 16:27:49 2010 Subject: [Haskell-beginners] foldr for Nats In-Reply-To: <20100201202048.41080@gmx.net> References: <20100126105245.288430@gmx.net> <5fdc56d71001260305h3a55380bv78e2732d68976708@mail.gmail.com> <20100201202048.41080@gmx.net> Message-ID: <5fdc56d71002011356t48e592cp91a7ff8cc1e4bef7@mail.gmail.com> Hello I'm suspecting this isn't homework as you've waited a week so would presumably have missed a deadline. As Daniel Fischer wrote, one view of folds is that they replace the constructors of a data type, code follows... data Nat = Z | S Nat deriving (Eq,Ord,Show) -- Look at the type of foldr... -- *GHCi> :t foldr -- foldr :: (a -> b -> b) -> b -> [a] -> b -- It has 2 'constructor replacements': -- (a -> b -> b) & b -- Replacing Z is easy, we can get some code to compile -- by avoiding the hard bit with a wildcard pattern "_"... foldrNat1 :: unknown -> b -> Nat -> b foldrNat1 _ b Z = b -- What to do about the constructor (S ..) takes a bit more -- thought or at least some experimenting. I'll do the later... -- One thing to try, is to simply translate foldr with as few -- changes as possible: -- foldr :: (a -> b -> b) -> b -> [a] -> b -- foldr _ z [] = z -- foldr f z (x:xs) = f x (foldr f z xs) -- Unfortunately this leads to a problem: foldrNat2 :: (Nat -> b -> b) -> b -> Nat -> b foldrNat2 f b Z = b -- Z case is the same as before foldrNat2 f b (S n) = f undefined (foldrNat2 f b n) -- Arggh! undefined -- undefined is useful for prototyping, but its a real -- problem for running code! -- Actually I had another problem as well... -- -- The difference between Nat and [a] is that List 'carries' some data -- therefore (Nat -> b -> b) on Nat is not equivalent to (a -> b -> b) -- on [a]. -- So rather than change the type signature first, get rid of the -- undefined and see what happens foldrNat3 f b Z = b foldrNat3 f b (S n) = f (foldrNat3 f b n) -- *GHCi> :t foldrNat3 -- > (t -> t) -> t -> Nat -> t -- GHCi likes to call type variables t, but the signature is equal to -- foldrNat3 :: (b -> b) -> b -> Nat -> b -- This looks promising - it typechecks! -- So try a test: fromNat :: Nat -> Int fromNat n = foldrNat3 (+1) 0 n demo1 = fromNat (S (S (S Z))) -- 3 ?? -- By experimenting we seem to have a good answer, -- other people might prefer a more rigorous proof though. From hjgtuyl at chello.nl Mon Feb 1 18:05:58 2010 From: hjgtuyl at chello.nl (Henk-Jan van Tuyl) Date: Mon Feb 1 17:37:26 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: <967918.68772.qm@web54304.mail.re2.yahoo.com> References: <201002011540.53154.daniel.is.fischer@web.de> <967918.68772.qm@web54304.mail.re2.yahoo.com> Message-ID: unxutils.zip seems to be gone; another option would be, to use MinGW/MSYS. You need this anyway for installing several Haskell packages that bind to C-software. If you start an MS-DOS shell and give command "sh", you are in a unixlike shell, where you can give the "time" command. Regards, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html -- On Mon, 01 Feb 2010 20:15:25 +0100, Tim Perry wrote: > CygWin would be a good option. > > Here are some other ideas: > > There is a timeit.exe utility in the Windows Server downloads which is > supposed to be similar to unix's time command. Try the links here > http://channel9.msdn.com/forums/Coffeehouse/258979-Windows-equivalent-of-UnixLinux-time-command/ > > Windows does support piping. It is similar to bash with 2>&1 to redirect > stderr to stdout and stuff. > http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true > > The new windows shell is almost a real shell. Almost. > > If you don't have that, then this port of unix utilities makes an XP box > tolerable. > http://unxutils.sourceforge.net/ > > Hope that helps. > --Tim > > > > ----- Original Message ---- > From: Daniel Fischer > To: Markus B?hm > Cc: beginners@haskell.org > Sent: Mon, February 1, 2010 6:40:52 AM > Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell > > Am Montag 01 Februar 2010 15:22:45 schrieb Markus B?hm: > >> Daniel, I use GHC 6.12.1 and Windows XP. > > *sigh* > > Have you a CygWin installed? It should run as given from a CygWin shell, > I > believe. > >> The time command doesn't seem >> to work. It says in German: specified time can't be read. Give a new >> time. > > Replace "time" with however you get the CPU time used by a process on > Windows. > But I think Windows doesn't allow piping, and I'm not sure whether it has > echo, so see below. > >> Daniel, here another feedback: >> >> F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop >> --make p 085-pi_lualoop.hs >> [1 of 1] Compiling Main ( p085-pi_lualoop.hs, >> p085-pi_lualoop.o ) Linking luaLoop.exe ... >> >> F:\MeineUebungen>echo '0.00000001' | time ./luaLoop >> Eingegebene Zeit kann nicht ?bernommen werden. >> Geben Sie die neue Zeit ein: >> >> F:\MeineUebungen>luaLoop +RTS -sstderr -RTS >> luaLoop +RTS -sstderr >> EPS: >> 0.00000001 >> 3.1415926485894725 >> 61,428 bytes allocated in the heap >> 1,316 bytes copied during GC >> 4,564 bytes maximum residency (1 sample(s)) >> 11,820 bytes maximum slop >> 1 MB total memory in use (0 MB lost due to fragmentation) >> >> Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s >> elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s >> elapsed >> >> INIT time 0.02s ( 0.00s elapsed) >> MUT time 8.06s ( 16.83s elapsed) >> GC time 0.00s ( 0.00s elapsed) >> EXIT time 0.00s ( 0.00s elapsed) >> Total time 8.08s ( 16.83s elapsed) >> >> %GC time 0.0% (0.0% elapsed) >> >> Alloc rate 7,604 bytes per MUT second >> >> Productivity 99.8% of total user, 47.9% of total elapsed > > What????? > > Please try the following: > > 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it > as > a command line argument) > 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop -- > make Source.hs > 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs > 4) cloop +RTS -sstderr > 5) nloop +RTS -sstderr > >> >> -- Markus >> > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- From felipe.lessa at gmail.com Mon Feb 1 18:37:37 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Mon Feb 1 18:17:29 2010 Subject: [Haskell-beginners] one more step backwards In-Reply-To: <4f7ad1ad1002011432g1e94570dg4795672f3a6c32f@mail.gmail.com> References: <4f7ad1ad1001310805g50944edchd82624f0f74da1c4@mail.gmail.com> <5fdc56d71001311052q611b2ebblfda2b541b699fef9@mail.gmail.com> <20100131195301.GA9576@kira.casa> <4f7ad1ad1002011432g1e94570dg4795672f3a6c32f@mail.gmail.com> Message-ID: <20100201233737.GA16183@kira.casa> On Mon, Feb 01, 2010 at 10:32:00PM +0000, John Moore wrote: > Hi Felipe, > this is way complicated for my level, could you look at this > below and see if I could use this instead. I understand you, it also took me some time to understand the monad transformer library :). > evalStep :: Expression -> Expression > evalStep (Val x)= (Val x) > evalStep (Add x y) > = case x of > (Val a) -> case y of > (Val b) -> Val (a+b) > left -> Add x (evalStep y) > right -> Add (evalStep x)y Even without the Writer monad you capture that pattern in an auxiliary function. You just extract the common bits and abstract the specific ones: aux calcOp mkOp x y = case x of (Val a) -> case y of (Val b) -> Val (a `calcOp` b) left -> mkOp x (evalStep y) right -> mkOp (evalStep x) y Note that: - I've changed (+) into calcOp and Add into mkOp. - Instead of deconstructing with a pattern match, I receive x and y as proper arguments. The type is type CalcOp = Integer -> Integer -> Integer type MkOp = Expression -> Expression -> Expression aux :: CalcOp -> MkOp -> Expression -> Expression -> (Expression -> Expression) You can write your evalStep as evalStep :: Expression -> Expression evalStep (Val x) = Val x evalStep (Add x y) = aux (+) Add x y evalStep (Subtract x y) = aux (-) Subtract x y evalStep (Multiply x y) = aux (*) Multiply x y evalStep (Divide x y) = aux div Divide x y Much cleaner ;). > What I mean to do is build up a history on a list and then take it of a > list( Same principle as a stack but a little more simple) the problem is how > do I get the other elements back of the list as in the line "r" -> evaluate > (I'm not sure what I put here) Hopes this makes some sort of sense. It does makes sense. In most languages this is the sort of code you would write: when the user tell us to evaluate, we evaluate and then save the result. However in our language we can leverage the laziness: buildHistory :: Expression -> [Expression] buildHistory expr = expr : buildHistory (evalStep) You may recognize this function as buildHistory = iterate evalStep (Note that unless your expression is infinite, then this list will contain an infinite number of duplicates when we reach the fixed point of the evalStep function.) The idea is to take everything you can out of IO. With buildHistory we take the logic of evaluating the expressions further out of IO. Now your function is as trivial as mine. In fact, it is the same. HTH, -- Felipe. From es at ertes.de Tue Feb 2 01:15:03 2010 From: es at ertes.de (Ertugrul Soeylemez) Date: Tue Feb 2 00:46:37 2010 Subject: [Haskell-beginners] Re: foldl' vs seq References: <22d241861002010354y2a34eae5u719050c7c6502a0f@mail.gmail.com> Message-ID: <20100202071503.241a853e@tritium.streitmacht.eu> Gabi wrote: > Hi Stephen, > Thanks for the answer. Now I got confused :) > > 1. What is seq used for if it doesn't force strictness ? > 2. Why the accumulator is important ? In other words why the following > is much slower ? Isn't it RT too ? > > slowSum :: [Integer] -> Integer > slowSum[] = 0 > slowSum (x:xs) = x `seq` x + slowSum xs Hello Gabi, The seq function may not behave as you expect it to. The following GHCi session may help you understand this: Prelude> const 3 (seq undefined 0) 3 Prelude> snd (seq undefined 0, 1) 1 Prelude> fst (seq undefined 0, 1) *** Exception: Prelude.undefined When the result of 'seq x y' is demanded, x is evaluated and then y is returned as that result. In the above session the first two expressions never evaluate the seq call. Haskell is lazy, so if you demand only the second value of a tuple, the first one is never evaluated, even if it contains 'seq x y'. However, _if_ it is evaluated, it will evaluate x first, then return y. Your statement, x `seq` x + slowSum xs, can be rewritten in the following way, seq x (x + slowSum xs), which makes clearer what it means: Upon evaluating x + slowSum xs, the value of x should be evaluated. In other words, your function builds the following result thunk: slowSum [1,2,3] = 1 + 2 + 3 + 0 instead of: slowSum [1,2,3] = THUNK + THUNK + THUNK + 0 But it still builds a thunk, which will have to actually perform all the additions. Why? Because nothing demands that sum until after all those recursive calls return. You are right in that a 'seq' is needed somewhere, but not where you put it. In fact the slowSum function cannot be optimized any further, because it is not tail-recursive: slowSum [1,2,3] => 1 + slowSum [2,3] Using prefix notation shows why the recursive call to slowSum is not the last function call and hence is no tail recursion: (+) 1 (slowSum [2,3]) The problem of non-tail recursion is that the recursive calls have no access to the "current result". You cannot force the addition from slowSum, because it's out of scope. If you introduce an accumulation parameter, things change: fastSum :: Num a => a -> [a] -> a fastSum s [] = s fastSum s (x:xs) = fastSum (s+x) xs Read it like: 'fastSum s xs' is the sum of the elements of xs plus the value of s. Reading it that way the code is self-explanatory, and clearly it is tail-recursive, giving the function full access to the current intermediary result (named s). It builds the following result: fastSum 0 [1,2,3] => fastSum (0 + THUNK) [2,3] => fastSum (0 + THUNK + THUNK) [3] => fastSum (0 + THUNK + THUNK + THUNK) [] => 0 + THUNK + THUNK + THUNK Well, now it is tail-recursive, so it doesn't eat stack space anymore, but it still builds that result expression instead of just giving the end result. This is where seq comes into play. Now that you have access to the intermediary result, you can force it to be evaluated along the way: superFastSum :: Num a => a -> [a] -> a superFastSum s [] = s superFastSum s (x:xs) = s `seq` superFastSum (s+x) xs Note how semantics have changed now: superFastSum 0 [1,2,3] => 0 `seq` superFastSum (0+1) [2,3] => superFastSum (0+1) [2,3] => (0+1) `seq` superFastSum ((0+1)+2) [3] => superFastSum (1+2) [3] => (1+2) `seq` superFastSum ((1+2)+3) [] => superFastSum (3+3) [] => 3+3 The result of superFastSum on a non-empty list depends on a recursive call to itself, but it clearly states (through seq) that _before_ that call is evaluated, the value of s is evaluated. So each time it attempts to build a result expression, that expression is immediately reduced to a value, to which the next list element is added. The foldl' function can be used to encode such a recursion pattern conveniently. It's just like the superFastSum function, but takes an arbitrary accumulation function instead of (+): import Data.List foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f z [] = z foldl' f z (x:xs) = z `seq` foldl' f (f z x) xs superFastSum = foldl' (+) 0 superFastProduct = foldl' (*) 1 superFastLength = foldl' (\x y -> x + 1) 0 I hope that helps. Supplemental note #1: Haskell compilers generally don't do common subexpression elimination (CSE), because that may change language semantics. The following code will not behave as you may expect it to: f x `seq` print (f x) With CSE in mind, you would expect the seq not to change anything and just print the result, but this is wrong. In fact it will be twice as slow! The reason is that to the compiler the first 'f x' is not the same as the second 'f x'. If you want them to be the same, you need to make this explicit by giving them a common name: let y = f x in y `seq` print y This is called memoizing and will work as expected, i.e. the seq will not slow things down. You can avoid some lets and wheres using the strict function application operator: print $! f x Supplemental note #2: A better, memoizing foldl' implementation: foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f z [] = z foldl' f z (x:xs) = let r = f z x in r `seq` foldl' f r xs Supplemental note #3: I noticed that recent versions of GHC are smart enough to know where it makes no semantic difference to force certain calculations. That means you can write the implementations of superFastSum and foldl' without seq: superFastSumGHC = fastSum foldl' = foldl However, for compatibility reasons you should still use seq. Greets Ertugrul -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From bugspynet at gmail.com Tue Feb 2 04:41:40 2010 From: bugspynet at gmail.com (Gabi) Date: Tue Feb 2 04:13:19 2010 Subject: [Haskell-beginners] Re: foldl' vs seq Message-ID: <22d241861002020141t531f5clfd69652b141431a9@mail.gmail.com> Thank you Ertugrul, I think I got it now. My lesson here is to avoid recursion as much possible and use foldr' instead.There are too many pitfalls. -- Regards, Gabi http://bugspy.net From es at ertes.de Tue Feb 2 08:05:23 2010 From: es at ertes.de (Ertugrul Soeylemez) Date: Tue Feb 2 07:36:54 2010 Subject: [Haskell-beginners] Re: foldl' vs seq References: <22d241861002020141t531f5clfd69652b141431a9@mail.gmail.com> Message-ID: <20100202140523.462bb871@tritium.streitmacht.eu> Gabi wrote: > Thank you Ertugrul, > > I think I got it now. > My lesson here is to avoid recursion as much possible and use foldr' > instead.There are too many pitfalls. That's not what I wanted to say. It's good to understand recursion and non-strict semantics, so that you can use them together to write great programs. =) However, as soon as you start speaking Haskell fluently, you won't write out many recursions explicitly anymore. For most things there are combinators of some type, which you can use to express what you want. Finally you will like monads, because most programming patterns can be expressed conveniently in terms of them. That includes stateful computation, aborting, resuming, undoing, nondeterminism, failability, probabilistic computation and an arbitrary mixture of them. Greets Ertugrul -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From bayer at cpw.math.columbia.edu Tue Feb 2 10:06:52 2010 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Tue Feb 2 09:38:23 2010 Subject: [Haskell-beginners] Monadic composition without throwing genericity under the bus? In-Reply-To: <20090203141712.GA24679@seas.upenn.edu> References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> Message-ID: <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> I've been playing with parsing, for text filtering applications such as an alternate GHC literate preprocessor. Here, it pays to have one's monad handle both the input and output streams out of sight. Using ShowS-valued monads, one can express most grammatical constructs as simple composition. I'm sure many people have had this idea, but the resulting parsers that I write end up much shorter than any demo code I've seen. For example, the "code is indented, comments are flush, periods delimit block comments" literate preprocessor that I depend on daily (leaving out the heredoc code) is just dot, comment, dotLine, commentLine, codeLine, dotBlock, delit ? Parser dot = char '.' comment = place "-- " codeLine = white ? till (heredoc ? whiteLine) word commentLine = comment ? line dotLine = comment ? dot ? whiteLine dotBlock = dotLine ? till (dotLine ? eof) (whiteLine ? commentLine) delit = till (skip (many whiteLine) ? eof) (whiteLine ? dotBlock ? codeLine ? commentLine) However, I've struggled mightily to cleanly implement composition of function-valued monads. In the end I had to throw genericity under the bus to use the above notation. I'm asking for help, in case I'm missing something. I cannot use Control.Category for a Monad, because of kind arity: Monad instances have one unbound *, while Category instances have two. Here are some toy experiments: mcompose ? Monad m ? m (b ? c) ? m (a ? b) ? m (a ? c) mcompose x y = do f ? x g ? y return $ f . g -- adapted from Control.Category class Category cat where unit ? cat a a compose ? cat b c ? cat a b ? cat a c instance Category (?) where unit = id compose = (.) -- Monad wrapper newtype Wrap m a b = Wrap { unwrap ? m (a ? b) } instance Monad m ? Category (Wrap m) where unit = Wrap $ return id compose x y = Wrap $ mcompose (unwrap x) (unwrap y) -- Other tries that fail instance Monad m ? Category (m (?)) where unit = return id compose = mcompose -- Error: -- The first argument of `Category' should have kind `* -> * -> *', -- but `m (->)' has kind `*' -- In the instance declaration for `Category (m (->))' type MonadMap m a b = m (a ? b) instance Monad m ? Category (MonadMap m) where unit = return id compose = mcompose -- Error: -- Type synonym `MonadMap' should have 3 arguments, but has been given 1 -- In the instance declaration for `Category (MonadMap m)' I can see why each of these fail, but I also crave a language that allows ambiguity if exactly one interpretation compiles. For example, one could scrape the leaves of the tree (m (?)) to find the two *'s one wants, and one would think that my MonadMap type synonym would be a standard trick for exposing the two *'s without giving up on the other form. (I want to use the same type as both a monad and a category, as the goal here is very concise code with no gunk packing and unpacking crutch types for the compiler.) So I threw "id" under the bus. Here are later experiments: mcompose ? Monad m ? m (b ? c) ? m (a ? b) ? m (a ? c) mcompose x y = do f ? x g ? y return $ f . g class Composable a b c | a b ? c where compose ? a ? b ? c instance Composable (b ? c) (a ? b) (a ? c) where compose f g = f . g instance Monad m ? Composable (m (b ? c)) (m (a ? b)) (m (a ? c)) where compose = mcompose unit ? Monad m ? m (a ? a) unit = return id tab ? Maybe ShowS tab = Just (" " ++) test1, test2 ? Monad m ? m (a ? a) test1 = mcompose unit unit test2 = compose unit unit -- test2 error: -- Could not deduce (Composable -- (m (a -> a)) (m1 (a1 -> a1)) (m2 (a2 -> a2))) -- from the context (Monad m2) -- arising from a use of `compose' at Issue2.lhs:26:10-27 test3, test4 ? Maybe ShowS test3 = mcompose tab tab test4 = compose tab tab It appears to me that type inference in type classes is broken. How else to explain why mcompose has no trouble figuring out that the monads are the same, but compose is stumped? In the end, I threw genericity under the bus, and chose the parser type type Parser = StateT String Maybe ShowS so the second approach would work in practice. I don't need to do this "my way" if there's an idiom (or -XAllowAliens compiler flag) that I need to learn. How does one do this sort of thing cleanly? Thanks! From daniel.is.fischer at web.de Tue Feb 2 11:08:44 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 10:42:10 2010 Subject: [Haskell-beginners] Monadic composition without throwing genericity under the bus? In-Reply-To: <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> References: <4987afcd.130c420a.134e.4097@mx.google.com> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> Message-ID: <201002021708.44296.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 16:06:52 schrieb Dave Bayer: > test1, test2 ? Monad m ? m (a ? a) > ? test1 = mcompose unit unit > ? test2 = compose ?unit unit > > -- test2 error: > -- Could not deduce (Composable > -- (m (a -> a)) (m1 (a1 -> a1)) (m2 (a2 -> a2))) > -- from the context (Monad m2) > -- arising from a use of `compose' at Issue2.lhs:26:10-27 > > ? test3, test4 ? Maybe ShowS > ? test3 = mcompose tab tab > ? test4 = compose ?tab tab > > It appears to me that type inference in type classes is broken. How else > to explain why mcompose has no trouble ?figuring out that the monads are > the same, but compose is stumped? Try removing the type signature for test2 and see what that gives: Compose.hs:28:8: No instance for (Composable (m (a -> a)) (m1 (a1 -> a1)) c) arising from a use of `compose' at Compose.hs:28:8-25 Possible fix: add an instance declaration for (Composable (m (a -> a)) (m1 (a1 -> a1)) c) In the expression: compose unit unit In the definition of `test2': test2 = compose unit unit Failed, modules loaded: none. commenting out test2 and querying the type at the prompt: *Compose> :t compose unit unit compose unit unit :: (Monad m, Monad m1, Composable (m (a -> a)) (m1 (a1 -> a1)) c) => c In mcompose, you specified exactly which types to use, in particular that there's only one monad involved. In test2, the type checker must determine the types from scratch. compose :: forall a b c. Composable a b c => a -> b -> c test2 = compose unit unit unit :: forall m a. Monad m => m (a -> a) The type checker can't assume that both unit's in test2 have the same type, so we have two monads (m, m1) and two types (a, a1) which are to be composed to give a third type (c). compose can only work when it knows the types of both arguments. It doesn't know the type of unit (since that's polymorphic), so it can't work with unit. You can help it somewhat by adding more FunDeps to Composable, class Composable a b c | a b ? c, a c -> b, b c -> a where compose ? a ? b ? c , then it can work when it knows a) the types of both arguments or b) the type of one argument and the type of the result. Doesn't help with test2, though. From perry2of5 at yahoo.com Tue Feb 2 12:34:38 2010 From: perry2of5 at yahoo.com (Tim Perry) Date: Tue Feb 2 12:36:19 2010 Subject: [Haskell-beginners] Performance of Idiomatic lazy Haskell In-Reply-To: References: <201002011540.53154.daniel.is.fischer@web.de> <967918.68772.qm@web54304.mail.re2.yahoo.com> Message-ID: <862123.41742.qm@web54303.mail.re2.yahoo.com> The links are confusing, but unxutils is still available: http://sourceforge.net/projects/unxutils/ MinGW/MSYS may be a better and/or more fully supported package but I have no experience there. Anyhow, time is built into the unxutils "sh" shell: C:\Documents and Settings\perry>sh WREN# time sleep 3 sleep 3 0.00s user 0.00s system 0% cpu 3.125 total WREN# However, I'm pretty sure the shell is actually zsh, not sh. ----- Original Message ---- From: Henk-Jan van Tuyl To: Tim Perry ; Daniel Fischer ; Markus B?hm Cc: beginners@haskell.org Sent: Mon, February 1, 2010 3:05:58 PM Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell unxutils.zip seems to be gone; another option would be, to use MinGW/MSYS. You need this anyway for installing several Haskell packages that bind to C-software. If you start an MS-DOS shell and give command "sh", you are in a unixlike shell, where you can give the "time" command. Regards, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ http://members.chello.nl/hjgtuyl/tourdemonad.html -- On Mon, 01 Feb 2010 20:15:25 +0100, Tim Perry wrote: > CygWin would be a good option. > > Here are some other ideas: > > There is a timeit.exe utility in the Windows Server downloads which is > supposed to be similar to unix's time command. Try the links here > http://channel9.msdn.com/forums/Coffeehouse/258979-Windows-equivalent-of-UnixLinux-time-command/ > > Windows does support piping. It is similar to bash with 2>&1 to redirect > stderr to stdout and stuff. > http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true > > The new windows shell is almost a real shell. Almost. > > If you don't have that, then this port of unix utilities makes an XP box > tolerable. > http://unxutils.sourceforge.net/ > > Hope that helps. > --Tim > > > > ----- Original Message ---- > From: Daniel Fischer > To: Markus B?hm > Cc: beginners@haskell.org > Sent: Mon, February 1, 2010 6:40:52 AM > Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell > > Am Montag 01 Februar 2010 15:22:45 schrieb Markus B?hm: > >> Daniel, I use GHC 6.12.1 and Windows XP. > > *sigh* > > Have you a CygWin installed? It should run as given from a CygWin shell, > I > believe. > >> The time command doesn't seem >> to work. It says in German: specified time can't be read. Give a new >> time. > > Replace "time" with however you get the CPU time used by a process on > Windows. > But I think Windows doesn't allow piping, and I'm not sure whether it has > echo, so see below. > >> Daniel, here another feedback: >> >> F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop >> --make p 085-pi_lualoop.hs >> [1 of 1] Compiling Main ( p085-pi_lualoop.hs, >> p085-pi_lualoop.o ) Linking luaLoop.exe ... >> >> F:\MeineUebungen>echo '0.00000001' | time ./luaLoop >> Eingegebene Zeit kann nicht ?bernommen werden. >> Geben Sie die neue Zeit ein: >> >> F:\MeineUebungen>luaLoop +RTS -sstderr -RTS >> luaLoop +RTS -sstderr >> EPS: >> 0.00000001 >> 3.1415926485894725 >> 61,428 bytes allocated in the heap >> 1,316 bytes copied during GC >> 4,564 bytes maximum residency (1 sample(s)) >> 11,820 bytes maximum slop >> 1 MB total memory in use (0 MB lost due to fragmentation) >> >> Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s >> elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s >> elapsed >> >> INIT time 0.02s ( 0.00s elapsed) >> MUT time 8.06s ( 16.83s elapsed) >> GC time 0.00s ( 0.00s elapsed) >> EXIT time 0.00s ( 0.00s elapsed) >> Total time 8.08s ( 16.83s elapsed) >> >> %GC time 0.0% (0.0% elapsed) >> >> Alloc rate 7,604 bytes per MUT second >> >> Productivity 99.8% of total user, 47.9% of total elapsed > > What????? > > Please try the following: > > 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it > as > a command line argument) > 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop -- > make Source.hs > 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs > 4) cloop +RTS -sstderr > 5) nloop +RTS -sstderr > >> >> -- Markus >> > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- From legajid at free.fr Tue Feb 2 16:21:25 2010 From: legajid at free.fr (legajid) Date: Tue Feb 2 15:47:51 2010 Subject: [Haskell-beginners] Using Debug.Trace In-Reply-To: <201001311133.01102.daniel.is.fischer@web.de> References: <4B654CA6.7000308@free.fr> <201001311133.01102.daniel.is.fischer@web.de> Message-ID: <4B689755.6030509@free.fr> Hi, it works fine, except (xv1,ok1) = calcul'' pxv c vallib `debug` (" " ++ show xv1) `debug` (" Calcul' ok1=" ++ show ok1 ++ " c:cs= " ++ show (c:cs)) that causes an infinite loop, cause xv1 and ok1 are just being calculated. Thank you for your clear explanation of do statements. Didier. Daniel Fischer a ?crit : > Am Sonntag 31 Januar 2010 10:25:58 schrieb legajid: > >> Hi, >> >> Starting with trace, i have trouble with my calcul'' function while >> calcul' is ok. >> When afftrace in calcul'' is commented, the program compiles. >> When uncommented ( afftrace (" calcul'' vide") ), i get >> the following messages : >> >> ------------------------------------------------------------------------ >> ------------------- *Main> :r >> [1 of 1] Compiling Main ( sud3c.hs, interpreted ) >> >> sud3c.hs:62:3: >> Couldn't match expected type `[Char]' >> against inferred type `(Plateau, Char)' >> In a stmt of a 'do' expression: afftrace (" calcul'' vide") >> In the expression: >> do afftrace (" calcul'' vide") >> (pxv, False) >> In the definition of `calcul''': >> calcul'' pxv _ [] >> = do afftrace (" calcul'' vide") >> (pxv, False) >> Failed, modules loaded: none. >> ------------------------------------------------------------------------ >> ------------------- >> >> I don't understand why, in calcul', it's ok and why, in calcul'', it's >> problematic. Because return value of calcul'' is a tuple ? >> > > You defined > > >> afftrace x= if modetrace then trace x " " >> else " " >> > > If you ask ghci the type of that, you'll get > > ghci> :t afftrace > afftrace :: String -> [Char] > > (or afftrace :: [Char] -> [Char], or String -> String) > > since > > ghci> :t trace > trace :: String -> a -> a > > Now you use afftrace in a do-block, which means "afftrace x" must have type > > (Monad m) => m a > > for some m and a. > Well, afftrace x has type [Char], so m is [] and a is Char, fine. > > That means you can use afftrace in any calculation returning a list of some > kind (outside of do-blocks, also in other calculations). > > But calcul'' doesn't return a list, it returns a pair. So > > calcul'' pxv _ [] = afftrace (" calcul'' vide") >> (pxv,False) > > , which is what the first equation of calcul'' is desugared to, isn't well > typed. > > (>>) :: Monad m => m a -> m b -> m b > > afftrace " calcul'' vide" :: [] Char -- m === [], a === Char > > (pxv,False) :: (,) Plateau Bool -- m === ((,) Plateau), b === Bool > > > (actually, ((,) Plateau) is indeed a monad, but it's a different one from > [], so the expression is not well typed). > > You could > - modify calcul'' to return [(Plateau,Bool)] > - not use do-blocks just for the sake of tracing and restructure your code > (I recommend the second) > > infixl 0 `debug` > > debug = flip trace > > calcul' pxv [] = pxv `debug` " Calcul' vide" > calcul' pxv (c:cs) > | ok1 = calcul' xv1 cs `debug` " Calcul' suite" > | otherwise = pxv `debug` " Calcul' pas de valeur" > where > vallib = [1 .. length pxv] ++ [5 .. 7] > nbvlib = length vallib > (xv1,ok1) = calcul'' pxv c vallib `debug` (" " ++ show xv1) > `debug` (" Calcul' ok1=" ++ show ok1 ++ " > c:cs= " ++ show (c:cs)) > > calcul'' pxv _ [] = (pxv,False) `debug` " calcul'' vide" > calcul'' pxv c (li:lis) > | False `debug` " " ++ show pvx ++ "..." = undefined > | li == 4 || li `elem` pxv = calcul'' pxv c lis `debug` "quoi?" > | otherwise = (calcul'' pxv c li,True) `debug` " calcul'''" > > Now the code reads more natural (except for the "False `debug` ... " to > produce general debugging output), and removing the debugging output isn't > any harder. > > >> When my program is ok, should i remove all trace instructions (and >> associated do commands too) or just set my modetrace value to False ? >> >> > > Remove, resp. comment out. > > >> Thanks for helping, >> Didier >> >> Below my code : >> >> >> calcul' :: Plateau -> [Cellule] -> Plateau >> calcul' pxv [] = do >> afftrace (" Calcul' vide") >> pxv >> calcul' pxv (c:cs)= do >> afftrace (" Calcul' ok1="++show ok1++" c:cs= "++show >> (c:cs)) afftrace (" "++show xv1) >> >> if ok1 then do >> afftrace (" Calcul' suite") >> calcul' xv1 cs >> else do >> afftrace (" Calcul' pas de valeur") >> pxv >> where >> vallib=[1..length pxv]++[5..7] >> nbvlib=length vallib >> (xv1,ok1)=calcul'' pxv c vallib >> >> >> >> calcul'' :: Plateau -> Cellule -> [Valeur] -> (Plateau, Bool) >> calcul'' pxv _ [] = do >> --afftrace (" calcul'' vide") >> (pxv, False) >> >> calcul'' pxv c (li : lis) = do >> --afftrace (" "++show pxv) >> --afftrace (" "++show c ++ " "++show(li:lis)) >> v2 >> where >> v2= if (elem li pxv || li==4) >> then >> calcul'' pxv c lis >> else do >> --afftrace (" calcul'''") >> (calcul''' pxv c li, True) >> >> calcul''' :: Plateau -> Cellule -> Valeur -> Plateau >> calcul''' pxv c li = >> take (c-1) pxv ++ [li] ++ drop c pxv >> >> afftrace x= if modetrace then trace x " " >> else " " >> > > > From joe at fixieconsulting.com Tue Feb 2 16:18:50 2010 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Tue Feb 2 15:50:43 2010 Subject: [Haskell-beginners] hunit question Message-ID: I have a little binary search function and am trying to write tests for it in hunit. The below approach doesn't compile, because I'm attempting to build a list of tuples of different types, which isn't working for me. What's the appropriate way to do this test? http://gist.github.com/293031 import Test.HUnit import JoeBinarySearch -- Note: -- JoeBinarySearch.binary_search :: (Ord a) => [a] -> a -> Maybe Int assertions = [ ([1], 1, (Just 0)), ([1, 3], 1, (Just 0)), ([1, 3, 4], 4, (Just 2)), ([1,2,4,6,8,9,12,15,17,20], 17, (Just 8)), ([1,2,4,6,8,9,12,15,17,20], 20, (Just 9)), ("hello", 'l', (Just 2)), -- BOOM ([0.0, 1.5, 3.0], 3.0, (Just 2)), ([], 1, Nothing), ([1,3], 2, Nothing), ([1,4,6,8,9,12,15,17,20], 2, Nothing), ([1,4,6,8,9,12,15,17,20], 100, Nothing), ([1,4,6,8,9,12,15,17,20], (-100), Nothing)] test_list = TestList test_cases where test_cases = map test_func assertions test_func (lst, input, expected) = TestCase $ assert_equal' ( binary_search lst input ) expected assert_equal' = assertEqual "should equal" main :: IO () main = do runTestTT test_list print "DONE" -- Joe Van Dyk http://fixieconsulting.com From kane96 at gmx.de Tue Feb 2 16:20:03 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Tue Feb 2 15:53:18 2010 Subject: [Haskell-beginners] define action getInt like getLine Message-ID: <20100202212003.55050@gmx.net> Hi, how can I write an action getInt :: IO Int that works like getLine :: IO String but for Int instead of String. I know that I can read the input with getLine and then convert it by using read, but don't know how to write it as an action. I tried getInt :: IO Int getInt read <- getLine but that doesn't work. -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From daniel.is.fischer at web.de Tue Feb 2 16:34:54 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 16:08:16 2010 Subject: [Haskell-beginners] hunit question In-Reply-To: References: Message-ID: <201002022234.54724.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 22:18:50 schrieb Joe Van Dyk: > I have a little binary search function and am trying to write tests > for it in hunit. > > The below approach doesn't compile, because I'm attempting to build a > list of tuples of different types, which isn't working for me. > > What's the appropriate way to do this test? QuickCheck, I'd say. Let that create more testcases than you could bother to write out. Anyway, for testing lists of different types, you'd need separate tests (properties/assertions). *But* you don't need that. Because the algorithm is general (works the same way for all types in Ord), the only way it could be correct on one type but not on another is if the Ord instance of one (or both) of the types is incorrect. So it's sufficient to test on [Int]. > > http://gist.github.com/293031 > > import Test.HUnit > import JoeBinarySearch > -- Note: > -- JoeBinarySearch.binary_search :: (Ord a) => [a] -> a -> Maybe Int > > assertions = [ > ([1], 1, (Just 0)), > ([1, 3], 1, (Just 0)), > ([1, 3, 4], 4, (Just 2)), > ([1,2,4,6,8,9,12,15,17,20], 17, (Just 8)), > ([1,2,4,6,8,9,12,15,17,20], 20, (Just 9)), > ("hello", 'l', (Just 2)), -- BOOM > ([0.0, 1.5, 3.0], 3.0, (Just 2)), > ([], 1, Nothing), > ([1,3], 2, Nothing), > ([1,4,6,8,9,12,15,17,20], 2, Nothing), > ([1,4,6,8,9,12,15,17,20], 100, Nothing), > ([1,4,6,8,9,12,15,17,20], (-100), Nothing)] > > test_list = TestList test_cases > where > test_cases = map test_func assertions > test_func (lst, input, expected) = TestCase $ assert_equal' ( > binary_search lst input ) expected > assert_equal' = assertEqual "should equal" > > main :: IO () > main = do > runTestTT test_list > print "DONE" From joe at fixieconsulting.com Tue Feb 2 16:36:44 2010 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Tue Feb 2 16:08:34 2010 Subject: [Haskell-beginners] Re: hunit question In-Reply-To: References: Message-ID: On Tue, Feb 2, 2010 at 1:18 PM, Joe Van Dyk wrote: > I have a little binary search function and am trying to write tests > for it in hunit. > > The below approach doesn't compile, because I'm attempting to build a > list of tuples of different types, which isn't working for me. > > What's the appropriate way to do this test? > > http://gist.github.com/293031 > > import Test.HUnit > import JoeBinarySearch > -- Note: > -- JoeBinarySearch.binary_search :: (Ord a) => [a] -> a -> Maybe Int > > assertions = [ > ?([1], ? ? ? 1, (Just 0)), > ?([1, 3], ? ?1, (Just 0)), > ?([1, 3, 4], 4, (Just 2)), > ?([1,2,4,6,8,9,12,15,17,20], 17, (Just 8)), > ?([1,2,4,6,8,9,12,15,17,20], 20, (Just 9)), > ?("hello", ? ? ? ? ? ? ? ? 'l', (Just 2)), -- BOOM > ?([0.0, 1.5, 3.0], ? ? ? ? 3.0, (Just 2)), > ?([], ? ? ? ? ? ? ? ? ? ? ?1, Nothing), > ?([1,3], ? ? ? ? ? ? ? ? ? 2, Nothing), > ?([1,4,6,8,9,12,15,17,20], 2, Nothing), > ?([1,4,6,8,9,12,15,17,20], 100, Nothing), > ?([1,4,6,8,9,12,15,17,20], (-100), Nothing)] > > test_list = TestList test_cases > ?where > ? ?test_cases = map test_func assertions > ? ?test_func (lst, input, expected) = TestCase $ assert_equal' ( > binary_search lst ?input ) expected > ? ?assert_equal' = assertEqual "should equal" > > main :: IO () > main = do > ?runTestTT test_list > ?print "DONE" I suppose I can live with this: build_test_case list element expected = test_case where test_case = TestCase assertion assertion = assertEqual "should equal" (binary_search list element) expected test_list = TestList [ build_test_case [1] 1 (Just 0), build_test_case [1, 3] 1 (Just 0), build_test_case [1, 3, 4] 4 (Just 2), build_test_case [1,2,4,6,8,9,12,15,17,20] 17 (Just 8), build_test_case [1,2,4,6,8,9,12,15,17,20] 20 (Just 9), build_test_case "hello" 'l' (Just 2), build_test_case [0.0, 1.5, 3.0] 3.0 (Just 2), build_test_case [] 1 Nothing, build_test_case [1,3] 2 Nothing, build_test_case [1,4,6,8,9,12,15,17,20] 2 Nothing, build_test_case [1,4,6,8,9,12,15,17,20] 100 Nothing, build_test_case [1,4,6,8,9,12,15,17,20] (-100) Nothing ] main :: IO () main = do runTestTT test_list print "DONE" But I assume there's a better way. From rk at trie.org Tue Feb 2 16:39:34 2010 From: rk at trie.org (Rahul Kapoor) Date: Tue Feb 2 16:11:06 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <20100202212003.55050@gmx.net> References: <20100202212003.55050@gmx.net> Message-ID: > Hi, > how can I write an action > getInt :: IO Int > that works like > getLine :: IO String The most literal way to write getInt would be: getInt :: IO Int getInt = do s <- getLine return (read s) which is just a more verbose version of: getInt' = read `fmap` getLine The above versions don't do any error checking, so you might prefer a getInt :: IO Maybe Int which returns Nothing in case the input is not an integer. You should read up on Monadic IO in Haskell. The Real World Haskell book is probably a good starting point. Rahul From daniel.is.fischer at web.de Tue Feb 2 16:39:07 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 16:12:28 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <20100202212003.55050@gmx.net> References: <20100202212003.55050@gmx.net> Message-ID: <201002022239.08105.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: > Hi, > how can I write an action > getInt :: IO Int > that works like > getLine :: IO String > but for Int instead of String. I know that I can read the input with > getLine and then convert it by using read, but don't know how to write > it as an action. I tried getInt :: IO Int > getInt read <- getLine > but that doesn't work. There are many possibilities. The shortest is getInt :: IO Int getInt = readLn another short and sweet is getInt :: IO Int getInt = fmap read getLine -- or liftM read getLine But neither of these deals well with malformed input, if that's a possibility to reckon with, use e.g. the reads function getInt :: IO Int getInt = do inp <- getLine case reads inp of ((a,tl):_) | all isSpace tl -> return a _ -> handle malformed input From joe at fixieconsulting.com Tue Feb 2 16:46:20 2010 From: joe at fixieconsulting.com (Joe Van Dyk) Date: Tue Feb 2 16:18:12 2010 Subject: [Haskell-beginners] hunit question In-Reply-To: <201002022234.54724.daniel.is.fischer@web.de> References: <201002022234.54724.daniel.is.fischer@web.de> Message-ID: On Tue, Feb 2, 2010 at 1:34 PM, Daniel Fischer wrote: > Am Dienstag 02 Februar 2010 22:18:50 schrieb Joe Van Dyk: >> I have a little binary search function and am trying to write tests >> for it in hunit. >> >> The below approach doesn't compile, because I'm attempting to build a >> list of tuples of different types, which isn't working for me. >> >> What's the appropriate way to do this test? > > QuickCheck, I'd say. Let that create more testcases than you could bother > to write out. > > Anyway, for testing lists of different types, you'd need separate tests > (properties/assertions). > > *But* you don't need that. Because the algorithm is general (works the same > way for all types in Ord), the only way it could be correct on one type but > not on another is if the Ord instance of one (or both) of the types is > incorrect. > > So it's sufficient to test on [Int]. Good point, but I like to prove that to myself. :D Any chance anyone can show me how to write a QuickCheck test for this? Joe From legajid at free.fr Tue Feb 2 17:06:41 2010 From: legajid at free.fr (legajid) Date: Tue Feb 2 16:33:05 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: References: <20100202212003.55050@gmx.net> Message-ID: <4B68A1F1.4060904@free.fr> Hi, here's another idea : saisie_choix :: IO Int saisie_choix=do putStrLn "Type in 1 digit :" xchoix <- getLine if (length xchoix) /= 1 || head xchoix < '0' || head xchoix > '9' then saisie_choix else do let nchoix=read xchoix::Int return nchoix or, with maybe : {- -------------- MAYBE ------------------ -} -- Fonction principale mainmaybe=do x <- lire if isNothing x then do putStrLn "Donnee invalide" else do putStr " \b" putStrLn ("Resultat : " ++ show (f x)) -- D?finition de la fonction de calcul f Nothing = -9999 f (Just x) = 2 * x -- Fonction d'IO qui valide la saisie lire :: IO (Maybe Integer) lire = do -- saisie xn <- getLine let x=read xn ::Integer -- validation if x < 5 then do return (Just x) else do return Nothing Didier. Rahul Kapoor a ?crit : >> Hi, >> how can I write an action >> getInt :: IO Int >> that works like >> getLine :: IO String >> > > The most literal way to write getInt would be: > > getInt :: IO Int > getInt = do > s <- getLine > return (read s) > > which is just a more verbose version of: > > getInt' = read `fmap` getLine > > The above versions don't do any error checking, so you might > prefer a getInt :: IO Maybe Int which returns Nothing in case the input > is not an integer. > > You should read up on Monadic IO in Haskell. The Real World Haskell book > is probably a good starting point. > > Rahul > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From daniel.is.fischer at web.de Tue Feb 2 17:03:48 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 16:39:15 2010 Subject: [Haskell-beginners] hunit question In-Reply-To: References: <201002022234.54724.daniel.is.fischer@web.de> Message-ID: <201002022303.48602.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 22:46:20 schrieb Joe Van Dyk: > On Tue, Feb 2, 2010 at 1:34 PM, Daniel Fischer wrote: > > Am Dienstag 02 Februar 2010 22:18:50 schrieb Joe Van Dyk: > >> I have a little binary search function and am trying to write tests > >> for it in hunit. > >> > >> The below approach doesn't compile, because I'm attempting to build a > >> list of tuples of different types, which isn't working for me. > >> > >> What's the appropriate way to do this test? > > > > QuickCheck, I'd say. Let that create more testcases than you could > > bother to write out. > > > > Anyway, for testing lists of different types, you'd need separate > > tests (properties/assertions). > > > > *But* you don't need that. Because the algorithm is general (works the > > same way for all types in Ord), the only way it could be correct on > > one type but not on another is if the Ord instance of one (or both) of > > the types is incorrect. > > > > So it's sufficient to test on [Int]. > > Good point, but I like to prove that to myself. :D > > Any chance anyone can show me how to write a QuickCheck test for this? > > Joe prop_binary_search :: Int -> [Int] -> Bool prop_binary_search x xs = let ys = sort xs in binary_search x ys == elemIndex x ys ghci> quickCheck prop_binary_search +++ OK, passed 100 tests. From daniel.is.fischer at web.de Tue Feb 2 17:16:01 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 16:49:31 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <4B68A1F1.4060904@free.fr> References: <20100202212003.55050@gmx.net> <4B68A1F1.4060904@free.fr> Message-ID: <201002022316.01778.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 23:06:41 schrieb legajid: > -- D?finition de la fonction de calcul > f Nothing = -9999 > f (Just x) = 2 * x That's already in the standard libs: ghci> :t maybe maybe :: b -> (a -> b) -> Maybe a -> b ghci> maybe (-9999) (*2) (Just $ fromEnum 'k') 214 From daniel.is.fischer at web.de Tue Feb 2 17:37:18 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 17:10:45 2010 Subject: [Haskell-beginners] hunit question In-Reply-To: <201002022303.48602.daniel.is.fischer@web.de> References: <201002022303.48602.daniel.is.fischer@web.de> Message-ID: <201002022337.18347.daniel.is.fischer@web.de> Am Dienstag 02 Februar 2010 23:03:48 schrieb Daniel Fischer: > Am Dienstag 02 Februar 2010 22:46:20 schrieb Joe Van Dyk: > > > > Any chance anyone can show me how to write a QuickCheck test for this? > > > > Joe > > prop_binary_search :: Int -> [Int] -> Bool > prop_binary_search x xs = > let ys = sort xs > in binary_search x ys == elemIndex x ys > > > ghci> quickCheck prop_binary_search > +++ OK, passed 100 tests. Ah, but: ghci> quickCheckWith (stdArgs { maxSuccess = 10000, maxDiscard = 1000, maxSize = 2000 }) prop_binary_search *** Failed! Falsifiable (after 8007 tests and 3 shrinks): -1 [-1,-1] Okay, does that mean my function is wrong? In this case, no, my test was wrong. I intended binary_search to be used only on *strictly* ascending lists, so change the test to import Data.IntSet (fromList, toAscList) prop_binary_search :: Int -> [Int] -> Bool prop_binary_search x xs = let ys = toAscList (fromList xs) in binary_search x ys == elemIndex x ys Now: ghci> quickCheckWith (stdArgs { maxSuccess = 10000, maxDiscard = 1000, maxSize = 2000 }) prop_binary_search +++ OK, passed 10000 tests. or perhaps a different test: prop_binary_search_2 :: Int -> [Int] -> Bool prop_binary_search_2 x xs = let ys = sort xs in case binary_search x ys of Nothing -> x `notElem` ys Just k -> x == ys !! k From markwvh at gmail.com Tue Feb 2 19:19:49 2010 From: markwvh at gmail.com (Mark Wong-VanHaren) Date: Tue Feb 2 18:51:20 2010 Subject: [Haskell-beginners] Problems installing TagSoup.Parsec In-Reply-To: <201002012142.14394.daniel.is.fischer@web.de> References: <201002012142.14394.daniel.is.fischer@web.de> Message-ID: Hi, Daniel- Many thanks for your help. Your instructions were very clear and worked perfectly. The only snag I encountered was a separate problem I had created for myself, which I'll mention here in case it may help someone else... I (thought I) wanted to uninstall TagSoup 0.8. (I didn't really need to.) Cabal doesn't provide an "uninstall" command, so I naively attempted to do it "manually" -- that is, to simply rm TagSoup-0.8-related files in my installation. This confused Cabal, which still "believed" (by virtue of config settings somewhere, presumably) that TagSoup was still installed. So cabal failed to find the actual files needed and complained. Rather than manually rm-ing things, the proper solution (I believe -- at least it worked for me) was to use "ghc-pkg unregister tagsoup". Anyway, thanks again for your help, Daniel. Cheers, -Mark 2010/2/1 Daniel Fischer : > Am Montag 01 Februar 2010 21:21:12 schrieb Mark Wong-VanHaren: >> Hi, folks- >> >> I'm a Haskell newbie. ?There's a very real chance my question has a >> simple answer. > > Yes and no. The problem is that the build-depends field of tagsoup- > parsec.cabal doesn't specify an upper bound on the version of tagsoup to > use. Thus cabal tries to build it with the latest and greates tagsoup, 0.8. > Neill Mitchell changed the tagsoup API, bad .cabal files break. > > Fix: unpack tagsoup-parsec-0.0.6, open the .cabal file, change > > > Library > ? Build-Depends: ?base<5, tagsoup, parsec<3 > > to > > Library > ? Build-Depends: ?base<5, tagsoup < 0.7, parsec<3 > > $ cd tagsoup-parsec-0.0.6 > $ cabal install > > email maintainer of tagsoup-parsec to fix it (adapt to new tagsoup API). > >> >> I wish to use the library Text.HTML.TagSoup.Parsec ( >> http://hackage.haskell.org/package/tagsoup-parsec), which looks very >> cool. >> >> When I attempt to install it, I get this error: >> >> # cabal install tagsoup-parsec >> Resolving dependencies... >> Configuring tagsoup-parsec-0.0.6... >> Preprocessing library tagsoup-parsec-0.0.6... >> Building tagsoup-parsec-0.0.6... >> [1 of 1] Compiling Text.HTML.TagSoup.Parsec ( >> Text/HTML/TagSoup/Parsec.hs, dist/build/Text/HTML/TagSoup/Parsec.o ) >> >> Text/HTML/TagSoup/Parsec.hs:37:5: >> ? ?`Tag' is not applied to enough type arguments >> ? ?Expected kind `*', but `Tag' has kind `* -> *' >> ? ?In the type synonym declaration for `WholeTag' >> cabal: Error: some packages failed to install: >> tagsoup-parsec-0.0.6 failed during the building phase. The exception >> was: exit: ExitFailure 1 >> >> >> It would seem to be a type mismatch between TagSoup.Parsec and the base >> TagSoup (on which it depends). >> >> Suspecting that the version-number dependency information might be >> incorrect, I tried uninstalling TagSoup and reinstalling an older >> version. This didn't help. >> >> Can anyone steer me in the right direction? >> >> Thanks! >> -Mark > > From daniel.is.fischer at web.de Tue Feb 2 19:44:09 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 2 19:17:30 2010 Subject: [Haskell-beginners] Problems installing TagSoup.Parsec In-Reply-To: References: <201002012142.14394.daniel.is.fischer@web.de> Message-ID: <201002030144.09804.daniel.is.fischer@web.de> Am Mittwoch 03 Februar 2010 01:19:49 schrieb Mark Wong-VanHaren: > Hi, Daniel- > > Many thanks for your help. Your instructions were very clear and > worked perfectly. > > The only snag I encountered was a separate problem I had created for > myself, which I'll mention here in case it may help someone else... > > I (thought I) wanted to uninstall TagSoup 0.8. (I didn't really need > to.) Cabal doesn't provide an "uninstall" command, so I naively > attempted to do it "manually" -- that is, to simply rm > TagSoup-0.8-related files in my installation. > > This confused Cabal, which still "believed" (by virtue of config > settings somewhere, presumably) Cabal asks ghc-pkg what is installed, it doesn't keep a separate database. > that TagSoup was still installed. So > cabal failed to find the actual files needed and complained. > > Rather than manually rm-ing things, the proper solution (I believe -- > at least it worked for me) was to use "ghc-pkg unregister tagsoup". Right. First unregister the packages. Then you can delete the files if you want to. > > Anyway, thanks again for your help, Daniel. Cheers, > -Mark From drg at david.gordon.name Tue Feb 2 21:43:30 2010 From: drg at david.gordon.name (David Gordon) Date: Tue Feb 2 21:15:22 2010 Subject: [Haskell-beginners] Cure me of my OOP ways Message-ID: Hi Folks, I am redesigning a system previously implemented in C++ using Haskell. I am keen to adopt a native programming style, but certain things about the original implementation still make perfect sense to me, including the C++-style subtype polymorphism. I'd be grateful if someone could take a look at the following sample and tell me if I'm missing some neater possible implementation in Haskell. {-# OPTIONS -fglasgow-exts #-} -- for existential types -- all subclasses take the same input format and can be created factory-pattern style data Input = Input Int Int -- this is the class we have to implement when creating a 'subtype' class InternalAPI i where doitImpl :: i -> Input -> Int -- factory function, everything is initialised by giving an "i" and the Input create :: i -> Input -> PublicAPI create a b = PublicAPI a b -- this is the object clients see, regardless of the underlying implementation data PublicAPI = forall p. InternalAPI p => PublicAPI p Input doit (PublicAPI p i) = doitImpl p i -- Here's an example implementation of something trivial data Adder = Adder instance InternalAPI Adder where doitImpl _ (Input a b) = a + b -- first argument is superfluous -- There's the factory function in use: test = create Adder (Input 1 2) result = doit test I'm actually pretty happy with this. I'm not trying for a complete OOP implementation but it lets me: - have the 'base class' (InternalAPI) implement default versions of methods with full access to the 'Input' structure containing the member data - do further inheritance, since I can select the implementation of a method using that first argument (e.g. on doitImpl) - base and derived classes see the same member data - Implementations of 'InternalAPI' can reference each other through the PublicAPI interface. Admittedly it's a rather vague question. I wonder if there are any articles out there showing how to reformulate problems solved using C++-style object models into Haskell programs? After all, it's hardly as if the C++ model is particularly elegant... thanks, David -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100202/b6738d4c/attachment.html From mutilating.cauliflowers.stephen at blacksapphire.com Wed Feb 3 01:19:14 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Wed Feb 3 00:50:53 2010 Subject: [Haskell-beginners] Cure me of my OOP ways In-Reply-To: References: Message-ID: <4B691562.8050702@blacksapphire.com> David, Here's the same code in more idiomatic Haskell: type API = Int -> Int -> Int test = 1 + 2 result = test I am being a smartypants, but only partly - I'm trying to make the point that partial application essentially replaces the factory pattern from OO. If you want to make another subclass, that has some extra internal data, e.g. 'add then scale by some value'... addAndScale :: Int -> API addAndScale f a b = (a + b) * f as10 = addAndScale 10 result = as10 3 5 These functions can't modify their internal state. If you want to add that capability, there are several ways. Here is one: newtype API = API {unAPI :: Int -> Int -> (Int, API) } sumTwo :: Int -> API sumTwo total = API $ \a b -> let total' = total + a + b in (total', sumTwo total') result = let s1 = sumTwo 0 (_, s2) = unAPI s1 2 2 (total, s3) = unAPI s2 3 7 in total This returns a new API, which the caller should now use instead of the old one, and this allows it to maintain state. The reason for the newtype is that things defined with 'type' can't be recursive. Steve David Gordon wrote: > Hi Folks, > > I am redesigning a system previously implemented in C++ using Haskell. I > am keen to adopt a native programming style, but certain things about > the original implementation still make perfect sense to me, including > the C++-style subtype polymorphism. I'd be grateful if someone could > take a look at the following sample and tell me if I'm missing some > neater possible implementation in Haskell. > > {-# OPTIONS -fglasgow-exts #-} > -- for existential types > > -- all subclasses take the same input format and can be created > factory-pattern style > data Input = Input Int Int > > -- this is the class we have to implement when creating a 'subtype' > class InternalAPI i where > doitImpl :: i -> Input -> Int > > -- factory function, everything is initialised by giving an "i" and > the Input > create :: i -> Input -> PublicAPI > create a b = PublicAPI a b > > -- this is the object clients see, regardless of the underlying > implementation > data PublicAPI = forall p. InternalAPI p => PublicAPI p Input > doit (PublicAPI p i) = doitImpl p i > > -- Here's an example implementation of something trivial > data Adder = Adder > instance InternalAPI Adder where > doitImpl _ (Input a b) = a + b -- first argument is superfluous > > -- There's the factory function in use: > test = create Adder (Input 1 2) > result = doit test > > I'm actually pretty happy with this. I'm not trying for a complete OOP > implementation but it lets me: > - have the 'base class' (InternalAPI) implement default versions of > methods with full access to the 'Input' structure containing the member data > - do further inheritance, since I can select the implementation of a > method using that first argument (e.g. on doitImpl) > - base and derived classes see the same member data > - Implementations of 'InternalAPI' can reference each other through the > PublicAPI interface. > > Admittedly it's a rather vague question. I wonder if there are any > articles out there showing how to reformulate problems solved using > C++-style object models into Haskell programs? After all, it's hardly as > if the C++ model is particularly elegant... > > thanks, > > David > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From bugspynet at gmail.com Wed Feb 3 03:50:57 2010 From: bugspynet at gmail.com (Gabi) Date: Wed Feb 3 03:22:29 2010 Subject: [Haskell-beginners] Fast tree manipulation Message-ID: <22d241861002030050x2fb482d2j9eaf2f3e30094015@mail.gmail.com> Hi I need to manipulate trees in great numbers and frequencies (lots of trees, lots of manipulations). What would be the right approach to achieve this and get good performance ? Maybe a library already exists ? -- Regards, Gabi http://bugspy.net From stephen.tetley at gmail.com Wed Feb 3 07:08:34 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 3 06:40:03 2010 Subject: [Haskell-beginners] Fast tree manipulation In-Reply-To: <22d241861002030050x2fb482d2j9eaf2f3e30094015@mail.gmail.com> References: <22d241861002030050x2fb482d2j9eaf2f3e30094015@mail.gmail.com> Message-ID: <5fdc56d71002030408k1ce444f1u1d0abb07d790af72@mail.gmail.com> Hi Gabi Performance will depend on the shape of the trees and the nature of the manipulations, so a general library won't really exist. What data do you have and what do you want to do with it? From bugspynet at gmail.com Wed Feb 3 07:47:01 2010 From: bugspynet at gmail.com (Gabi) Date: Wed Feb 3 07:18:30 2010 Subject: [Haskell-beginners] Fast tree manipulation Message-ID: <22d241861002030447ha94fe7n2ce179b2223f57ca@mail.gmail.com> I plan to implement some form of GP (GeneticProgramming) system. The trees would represent execution trees which means each node in the tree will represent a function, and leaves would represent terminals. An efficient GP system would fail if the tree manipulation operators (crossover, mutation) are slow. -- Regards, Gabi http://bugspy.net From stephen.tetley at gmail.com Wed Feb 3 09:42:58 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 3 09:14:27 2010 Subject: [Haskell-beginners] Fast tree manipulation In-Reply-To: <22d241861002030447ha94fe7n2ce179b2223f57ca@mail.gmail.com> References: <22d241861002030447ha94fe7n2ce179b2223f57ca@mail.gmail.com> Message-ID: <5fdc56d71002030642w471a4b4eg13dfeb03b0d0d652@mail.gmail.com> On 3 February 2010 12:47, Gabi wrote: > An efficient GP system would fail if the tree manipulation operators > (crossover, mutation) are slow. Impeccably true, by definition. There might some information to be gleaned from following the links here: http://www.haskell.org/haskellwiki/Applications_and_libraries/Genetic_programming ... but otherwise I can't find anything Haskell related by a quick search. While its not directly related, Robert Giegerich has done a lot of work with dynamic programming for Haskell for bio informatics and checking his work might interesting at least for 'methodology'. A paraphrase of the conclusion from his paper a decade ago[1] was that Haskell was invaluable for prototyping but C was essential for speed. Haskell (GHC) has got a lot faster in the decade since, but it seems for absolute speed his research group currently use a 'domain-specific compiler' written in Haskell that generates C. This line of 'off shore' optimization is a recurring theme in Haskell and has been explored by Conal Elliott and others for graphics. Best wishes Stephen [1] "An Algebraic Dynamic Programming Approach to the Analysis of Recombinant DNA Sequences" http://eref.uqu.edu.sa/files/an_algebraic_dynamic_programming_approac_2173614.pdf From bugspynet at gmail.com Wed Feb 3 10:12:52 2010 From: bugspynet at gmail.com (Gabi) Date: Wed Feb 3 09:44:21 2010 Subject: [Haskell-beginners] Fast tree manipulation Message-ID: <22d241861002030712v5d56da7bpde6188f4ce490119@mail.gmail.com> I might be wrong but I think this is a weak spot for many functional langs, including Haskell - The ability to manipulate in high rate data structures without killing the performance . Even in langs like Clojure, which enable the cheap creation of new modified structures out of old ones(using "persistent structures") -it is much slower than using an imperative language to manipulate data in place. What is the approach of Haskell to this ? -- Regards, Gabi http://bugspy.net From stephen.tetley at gmail.com Wed Feb 3 12:55:58 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 3 12:27:28 2010 Subject: [Haskell-beginners] Fast tree manipulation In-Reply-To: <22d241861002030712v5d56da7bpde6188f4ce490119@mail.gmail.com> References: <22d241861002030712v5d56da7bpde6188f4ce490119@mail.gmail.com> Message-ID: <5fdc56d71002030955r6d1457e4mfb62e62834eb3103@mail.gmail.com> Data structures in Haskell are persistent useless you use ST-refs or similar. Coupled with sharing this can bring some optimizations, e.g. here: http://www.haskell.org/pipermail/haskell-cafe/2009-May/061368.html Admittedly the efficiencies in that message are on somewhat trivial use-cases. Best wishes Stephen From bugspynet at gmail.com Wed Feb 3 14:53:18 2010 From: bugspynet at gmail.com (Gabi) Date: Wed Feb 3 14:24:54 2010 Subject: [Haskell-beginners] Fast tree manipulation Message-ID: <22d241861002031153r63f19733vc3ebaf6f792330ac@mail.gmail.com> Maybe Data.Sequence is a good option. Seems to be designed to give good performance when mutating If trees could be represented using Data.Sequence, I think that tree manipulation performance would be bearable. Any other libraries that might be useful? -- Regards, Gabi http://bugspy.net From mutilating.cauliflowers.stephen at blacksapphire.com Wed Feb 3 15:08:40 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Wed Feb 3 14:40:17 2010 Subject: [Haskell-beginners] Fast tree manipulation In-Reply-To: <22d241861002030712v5d56da7bpde6188f4ce490119@mail.gmail.com> References: <22d241861002030712v5d56da7bpde6188f4ce490119@mail.gmail.com> Message-ID: <4B69D7C8.1020207@blacksapphire.com> Gabi, If the structure is simple enough that it can be represented using arrays, or if you write it in IO using IORefs, you can do it, but idiomatic Haskell generally can't perform as well for the problem you describe as a language that updates in place. Even so, overall the compiler optimizes very well. Haskell is such a good language that you may be able to achieve the performance you want with IORefs (IORefs are _very_ fast), and even though it's not as pleasing as Haskell code can be, the code may still be better than you could do in an imperative language, but this would depend a bit on the details of your problem. Gabi wrote: > Maybe Data.Sequence is a good option. Seems to be designed to give > good performance when mutating > If trees could be represented using Data.Sequence, I think that tree > manipulation performance would be bearable. > Any other libraries that might be useful? I use Data.IntMap a lot, including a wrapped version that takes any Enum as a key (which I intend to put on Hackage some time). Data.IntMap, Data.Map and Data.Sequence are a bit slower than update-in-place languages, but algorithmically they're very good and the performance is definitely not terrible. You might be interested in taking a look at http://haskell.org/haskellwiki/DDC. Disciple is a Haskell-like language - with the project being at a very early stage - that includes mutability in its type system so you can mutate state in place, but with the same strong guarantees of purity that you get in Haskell with the ST and State monads. The compiler is incomplete but it does work for the core of the language, so it's possible to write small programs in it. Steve Gabi wrote: > I might be wrong but I think this is a weak spot for many functional > langs, including Haskell - The ability to manipulate in high rate data > structures without killing the performance . Even in langs like > Clojure, which enable the cheap creation of new modified structures > out of old ones(using "persistent structures") -it is much slower than > using an imperative language to manipulate data in place. What is the > approach of Haskell to this ? > From kwangraecho at gmail.com Tue Feb 2 04:32:08 2010 From: kwangraecho at gmail.com (=?EUC-KR?B?wbaxpLeh?=) Date: Wed Feb 3 20:21:19 2010 Subject: [Haskell-beginners] wanto post haskell question Message-ID: <98f46b31002020132y718d213dyc5da4a10c0b065ab@mail.gmail.com> hi I have a question about haskell coding. Matrices One of many ways to define matrices in Haskell is the list of matrix rows, where a row is a list of double precision oating point numbers: type Matrix=[[Double]] Using this type you should define the following functions (definition of dim is given as an inspirational example). dim :: Matrix -> (Int,Int) --returns matrix dimension (number of rows and columns) dim m = if (not.isMatrix) m then error "Not a matrix" else (length m, length (head m)) isMatrix :: Matrix -> Bool --checks whether all rows have the same length isMatrix m = and [length (head m) == length a | a <- m] I have done upto here and I am stuck on multSM. multSM :: Double -> Matrix -> Matrix --multiplies a scalar and a matrix when I do: multSM d m = [[(b*a)| b<-[d], a<-(head m)]] or [map (*d) (head m)] ...I get (using Hugs): Main> multSM 3 [[2,3,4],[1,3,4],[6,3,0]] [[6.0,9.0,12.0]] So I solve 3 [2,3,4] but I do not know how to get the rest 3 [[1,3,4],[6,3,0]. Please help me on this problem. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100202/3e0ef10d/attachment-0001.html From magnate.lee at gmail.com Wed Feb 3 21:39:28 2010 From: magnate.lee at gmail.com (Wonchan Lee) Date: Wed Feb 3 21:10:56 2010 Subject: [Haskell-beginners] wanto post haskell question In-Reply-To: <98f46b31002020132y718d213dyc5da4a10c0b065ab@mail.gmail.com> References: <98f46b31002020132y718d213dyc5da4a10c0b065ab@mail.gmail.com> Message-ID: <475e3e861002031839x3608d526x1caaaa5395175cef@mail.gmail.com> Hello, Kwangrae. I think the following function will work for you: multSM :: Double -> Matrix -> Matrix --multiplies a scalar and a matrix multSM d m = [ [d * b | b <- a] | a <- m] I just use nested list comprehension. 2010/2/2 ??? : > hi I have a question about haskell coding. > > Matrices > > One of many ways to define matrices in Haskell is the list of matrix rows, > where a row is a list of double precision oating point numbers: > > type Matrix=[[Double]] > > Using this type you should define the following functions (definition of dim > is given as an inspirational example). > > dim :: Matrix -> (Int,Int) --returns matrix dimension (number of rows and > columns) > dim m = if (not.isMatrix) m then error "Not a matrix" else (length m, length > (head m)) > > isMatrix :: Matrix -> Bool --checks whether all rows have the same length > isMatrix m = and [length (head m) == length a | a <- m] > > I have done upto here and I am stuck on multSM. > > multSM :: Double -> Matrix -> Matrix --multiplies a scalar and a matrix > > when I do: > > multSM d m = [[(b*a)| b<-[d], a<-(head m)]] or [map (*d) (head m)] > > ...I get (using Hugs): > > Main> multSM 3 [[2,3,4],[1,3,4],[6,3,0]] > [[6.0,9.0,12.0]] > > So I solve 3 [2,3,4] but I do not know how to get the rest 3 > [[1,3,4],[6,3,0]. > > Please help me on this problem. > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From bayer at cpw.math.columbia.edu Wed Feb 3 23:45:14 2010 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Wed Feb 3 23:16:40 2010 Subject: [Haskell-beginners] Monadic composition without throwing genericity under the bus? In-Reply-To: <201002021708.44296.daniel.is.fischer@web.de> References: <4987afcd.130c420a.134e.4097@mx.google.com> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <201002021708.44296.daniel.is.fischer@web.de> Message-ID: Let me be as concise as I can, for a second try. One can't make a function-valued monad into an instance of Category, because a Category takes two type arguments, while a Monad takes one? I'm having serious cognitive dissonance here. The "back 40 acres" of the GHC manual is filled with brilliant work-arounds and references to research papers for far more arcane type dilemmas than this. My local hardware store is filled with pieces of copper that fit 1/2" pipe to 3/4" pipe, and they don't check for Ph.Ds at the door. But there's no provision in the language to fit a type class taking two arguments to a type class taking one argument? I simply can't believe that I'm the first person to stumble over this. Either this is a famous rough edge, and others can list off a dozen similar circumstances where one gets stuck, or there's an easy work-around I'm just not seeing. Can anyone confirm that it's simply not possible to plumb type classes the way I want to plumb them? If so, should I be proposing a language extension on a different mailing list? On Feb 2, 2010, at 11:08 AM, Daniel Fischer wrote: > You can help it somewhat by adding more FunDeps to Composable, > > class Composable a b c | a b ? c, a c? b, b c? a where > compose ? a ? b ? c That's nice, I didn't think of that, but as you say it doesn't fix the problem. From apfelmus at quantentunnel.de Thu Feb 4 05:26:36 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Thu Feb 4 04:58:29 2010 Subject: [Haskell-beginners] Re: Fast tree manipulation In-Reply-To: <22d241861002031153r63f19733vc3ebaf6f792330ac@mail.gmail.com> References: <22d241861002031153r63f19733vc3ebaf6f792330ac@mail.gmail.com> Message-ID: Gabi wrote: > Maybe Data.Sequence is a good option. Seems to be designed to give > good performance when mutating > If trees could be represented using Data.Sequence, I think that tree > manipulation performance would be bearable. > Any other libraries that might be useful? I don't see why you would want to use Data.Sequence for representing trees. Trees are usually represented as data Tree a b = Leaf b | Branch a (Tree a b) (Tree a b) While trees are persistent, they are also shared; "mutating" a tree will only change a small part of it. And if you are doing a lot of local operations, a zipper may help http://en.wikibooks.org/wiki/Haskell/Zippers In any case, I'd recommend to go ahead and use the simplest possible representation of trees for a small prototype. If any performance problems crop up, ask the list again. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From stephen.tetley at gmail.com Thu Feb 4 05:35:50 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Feb 4 05:07:18 2010 Subject: [Haskell-beginners] Monadic composition without throwing genericity under the bus? In-Reply-To: References: <4987afcd.130c420a.134e.4097@mx.google.com> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <201002021708.44296.daniel.is.fischer@web.de> Message-ID: <5fdc56d71002040235u5f31c4aen52cd5346a7143757@mail.gmail.com> Hi Dave You might need more that a type system extension for this one. I've called your composition operator (*>>*), if you stack the type signatures together I can't see a way of getting from (*>>*) to (.). Compare it to the Kleisli composition of monads - where the step to (.) is more apparent (swap '-> m' for cat): -- (.) :: cat b c -> cat a b -> cat a c -- (.) :: b `cat` c -> a `cat` b -> a `cat` c -- infix -- (*>>*) :: Monad m => m (b -> c) -> m (a -> b) -> m (a -> c) -- Kleisli composition does satisfy Category -- _Kleisli_ :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c) I think I've derived what you are doing below with Graham Hutton's parser monad, the 'easy work around' is to use (*>>*) rather than try to use (.): module Fun where -- Starting with a Graham Hutton's parser as it is (probably) the -- simplest monadic parser newtype Parser a = Parser { parse :: (String -> [(a,String)]) } instance Monad Parser where return a = Parser (\cs -> [(a,cs)]) p >>= f = Parser (\cs -> concat [parse (f a) cs' | (a,cs') <- parse p cs]) item :: Parser Char item = Parser (\cs -> case cs of "" -> [] (c:cs) -> [(c,cs)]) zero :: Parser a zero = Parser (\cs -> []) sat :: (Char -> Bool) -> Parser Char sat p = do {c <- item; if p c then return c else zero} char0 :: Char -> Parser Char char0 c = sat (c==) char :: Char -> Parser ShowS char c = do {ch <- sat (c==) ; return (showChar c) } -- consume but don't produce ? place0 :: String -> Parser String place0 str = do { str' <- mapM char0 str; return "" } place :: String -> Parser ShowS place str = place0 str >> return (\s -> s) -- no string aka id string0 :: String -> Parser String string0 str = mapM char0 str string :: String -> Parser ShowS string str = do { str' <- string0 str; return (showString str) } -------------------------------------------------------------------------------- dot :: Parser ShowS dot = char '.' comment :: Parser ShowS comment = place "-- " runParser :: Parser ShowS -> String -> String runParser p inp = post $ ((parse p) inp) where post [(ans,_)] = ans $ "" post xs = error (unlines $ map (\(f,cs) -> show (f "",cs)) xs) demo1 :: String demo1 = runParser (comment >> dot) "-- ." startPragma :: Parser ShowS startPragma = string "{-#" demo2 :: String demo2 = runParser (startPragma) "{-#" space :: Parser ShowS space = char ' ' languageU :: Parser ShowS languageU = string "LANGUAGE" -- first attempt - 'endo' style keeps the same type (*>*) :: Monad m => m (a -> a) -> m (a -> a) -> m (a -> a) mf *>* mg = do { f <- mf; g <- mg; return (f.g) } demo3 :: String demo3 = runParser (startPragma *>* space *>* languageU) "{-# LANGUAGE" -- second attempt - 'bluebird' style - proper composition -- (more general) (*>>*) :: Monad m => m (b -> c) -> m (a -> b) -> m (a -> c) mf *>>* mg = do { f <- mf; g <- mg; return (f.g) } demo4 :: String demo4 = runParser (startPragma *>>* space *>>* languageU) "{-# LANGUAGE" -- (.) :: cat b c -> cat a b -> cat a c -- (*>>*) :: Monad m => m (b -> c) -> m (a -> b) -> m (a -> c) -- ??? -- Kleisli composition does satisfy Category -- _Kleisli_ :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c) -- TYPE ERROR -- demo5x :: String -- demo5x = runParser (startPragma . space . languageU) "{-# LANGUAGE" From apfelmus at quantentunnel.de Thu Feb 4 05:43:42 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Thu Feb 4 05:15:31 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: References: <4987afcd.130c420a.134e.4097@mx.google.com> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <201002021708.44296.daniel.is.fischer@web.de> Message-ID: Dave Bayer wrote: > Let me be as concise as I can, for a second try. > > One can't make a function-valued monad into an instance of Category, > because a Category takes two type arguments, while a Monad takes one? > [...] > I simply can't believe that I'm the first person to stumble over > this. Either this is a famous rough edge, and others can list off a > dozen similar circumstances where one gets stuck, or there's an easy > work-around I'm just not seeing. > > Can anyone confirm that it's simply not possible to plumb type > classes the way I want to plumb them? If so, should I be proposing a > language extension on a different mailing list? You want a composition of functors Wrap m ~ m ? (->) but since higher-kinded polymorphism is a bit limited in Haskell (decidability!), I don't think there's a way to make this an instance of Category directly. The usual solution is to make Wrap a newtype newtype Wrap m a b = Wrap (m (a -> b)) instance Monad m => Category (Wrap m) where ... and live with it. If you want to be a bit more generic, you can use a newtype to denote functor composition {-# LANGUAGE TypeSynonymInstances #-} newtype f `O` g a b = O (f (g a b)) instance Monad m => Category (m `O` (->)) where id = return id f . g = liftM2 (.) f g But in both cases, there is no way around the fact that the Category class needs a new type as argument. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From apfelmus at quantentunnel.de Thu Feb 4 05:46:28 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Thu Feb 4 05:21:32 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> Message-ID: Dave Bayer wrote: > I've been playing with parsing, for text filtering applications such > as an alternate GHC literate preprocessor. Here, it pays to have one's > monad handle both the input and output streams out of sight. Using > ShowS-valued monads, one can express most grammatical constructs as > simple composition. I'm sure many people have had this idea, but the > resulting parsers that I write end up much shorter than any demo code > I've seen. For example, the "code is indented, comments are flush, > periods delimit block comments" literate preprocessor that I depend on > daily (leaving out the heredoc code) is just > > dot, comment, dotLine, commentLine, codeLine, dotBlock, delit ? Parser > > dot = char '.' > comment = place "-- " > > codeLine = white ? till (heredoc ? whiteLine) word > commentLine = comment ? line > > dotLine = comment ? dot ? whiteLine > dotBlock = dotLine ? till (dotLine ? eof) (whiteLine ? commentLine) > > delit = till (skip (many whiteLine) ? eof) > (whiteLine ? dotBlock ? codeLine ? commentLine) This looks intriguing! Can you elaborate on how this works? Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From stephen.tetley at gmail.com Thu Feb 4 06:25:36 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Feb 4 05:57:03 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> Message-ID: <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> The parser has a type restricted return type - always a 'Hughes string' with efficient concatenation (ShowS :: String -> String) rather than some polymorphic answer (e.g a parse tree). For formatting it allows you to add text without consuming any: inserttext :: String -> Parser inserttext str = return (showString str) Or rewrite matched input: rewrite :: String -> String -> Parser rewrite inp out = string inp >> return (showString out) Or drop text, I presume this is what the place combinator does. Its a nice technique. On 4 February 2010 10:46, Heinrich Apfelmus wrote: > > This looks intriguing! Can you elaborate on how this works? From bugspynet at gmail.com Thu Feb 4 07:34:44 2010 From: bugspynet at gmail.com (Gabi) Date: Thu Feb 4 07:06:11 2010 Subject: [Haskell-beginners] Re: Fast tree manipulation Message-ID: <22d241861002040434q471e6ebk2a77f3bc12ff9b5c@mail.gmail.com> Hi Heinrich, I didn't see any mature zipper libraries to efficiently manipulate trees. Can you point me to any mature libs ? Aside from that, there are many reasons why I would represent trees using sequence. The major one is that many GA operations like 2 point crossover and mutation are trivial if we represent the genome in vectors or sequence instead of trees. The downside is the cost of the translation of sequences back to trees. -- Regards, Gabi http://bugspy.net From bayer at cpw.math.columbia.edu Thu Feb 4 08:26:32 2010 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Thu Feb 4 07:58:00 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> Message-ID: <0E678540-7FC3-4AF8-A461-ACEA338A2F09@math.columbia.edu> Thanks for all your answers. Yes, Stephen explains exactly what I'm doing. I had been using a literate preprocessor that could have been written in Basic, but didn't include heredocs. It was very short, but I wanted something more idiomatic, so I stared at everyone's parser tutorials, wondering about monadic -vs- applicative etc. etc. The twin irritations of do notation everywhere, and ++ everywhere, pushed me over the edge to try ShowS-valued monads, and I loved how the code looked. Normally I accept wrappers on everything as just how one does business in Haskell. As you say, to avoid undecidable type issues. Here I was struggling for days to make the code as lean as possible, and I could almost get away without wrappers. I've been following the migration convention of ASCII for historic Prelude, Unicode for generic version of same, so I didn't want to steal ?? for this one purpose; it should be categorical composition. I like the answer that m ?? (->) is simply something different, I shouldn't think of it as composition. I had been using ??? for this, I'll probably go back to it. For a simple parser tutorial, or my immediate application of munging text e.g. literate preprocessor, ok to hardwire ShowS-valued monads. However, when one does have to break down and go into do notation (e.g. to implement my heredocs which steal the indentation from the closing EOF, and otherwise looks cleaner with multiple parsing passes), it might be slicker to use a general (a ??? b) type in place of ShowS. In fact, I believe one could do anything other parsers do, this way, with the benefit of most expressions being composition not requiring do-notation. Anyhow, going further with monads returning (a ??? b) required me to make my peace with this composition issue, so I thank each of you! I will write up a tutorial on this form of parsing when I submit my literate preprocessor to Cabal. On Feb 4, 2010, at 6:25 AM, Stephen Tetley wrote: > The parser has a type restricted return type - always a 'Hughes > string' with efficient concatenation (ShowS :: String -> String) > rather than some polymorphic answer (e.g a parse tree). For formatting > it allows you to add text without consuming any: > > inserttext :: String -> Parser > inserttext str = return (showString str) > > Or rewrite matched input: > > rewrite :: String -> String -> Parser > rewrite inp out = string inp >> return (showString out) > > Or drop text, I presume this is what the place combinator does. > > Its a nice technique. > > On 4 February 2010 10:46, Heinrich Apfelmus wrote: >> >> This looks intriguing! Can you elaborate on how this works? > From hyangfji at gmail.com Thu Feb 4 15:46:39 2010 From: hyangfji at gmail.com (Hong Yang) Date: Thu Feb 4 15:18:05 2010 Subject: [Haskell-beginners] show vs. Data.ByteString.Char8.unpack for ByteString Message-ID: Hi, What is the difference between show and unpack when the function arguments are of ByteString type? I thought they are the same, but they are not interchangeable at compile time. Thanks, Hong -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100204/f5b18c1c/attachment.html From kane96 at gmx.de Thu Feb 4 15:58:45 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 4 15:30:17 2010 Subject: [Haskell-beginners] foldr for Nats In-Reply-To: <5fdc56d71002011356t48e592cp91a7ff8cc1e4bef7@mail.gmail.com> References: <20100126105245.288430@gmx.net> <5fdc56d71001260305h3a55380bv78e2732d68976708@mail.gmail.com> <20100201202048.41080@gmx.net> <5fdc56d71002011356t48e592cp91a7ff8cc1e4bef7@mail.gmail.com> Message-ID: <20100204205845.26700@gmx.net> @Stephan thanks for the code so far. @Daniel it should look like foldrNat a b S(S(S(S(Z)))) gives a(a(a(a(b)))) The thing is the definition have to be -------- Original-Nachricht -------- > Datum: Mon, 1 Feb 2010 21:56:14 +0000 > Von: Stephen Tetley > An: kane96@gmx.de > CC: Beginners@haskell.org > Betreff: Re: [Haskell-beginners] foldr for Nats > Hello > > I'm suspecting this isn't homework as you've waited a week so would > presumably have missed a deadline. > > As Daniel Fischer wrote, one view of folds is that they replace the > constructors of a data type, code follows... > > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > > -- Look at the type of foldr... > > -- *GHCi> :t foldr > -- foldr :: (a -> b -> b) -> b -> [a] -> b > > -- It has 2 'constructor replacements': > -- (a -> b -> b) & b > > -- Replacing Z is easy, we can get some code to compile > -- by avoiding the hard bit with a wildcard pattern "_"... > > foldrNat1 :: unknown -> b -> Nat -> b > foldrNat1 _ b Z = b > > -- What to do about the constructor (S ..) takes a bit more > -- thought or at least some experimenting. I'll do the later... > > -- One thing to try, is to simply translate foldr with as few > -- changes as possible: > > -- foldr :: (a -> b -> b) -> b -> [a] -> b > -- foldr _ z [] = z > -- foldr f z (x:xs) = f x (foldr f z xs) > > -- Unfortunately this leads to a problem: > > foldrNat2 :: (Nat -> b -> b) -> b -> Nat -> b > foldrNat2 f b Z = b -- Z case is the same as before > foldrNat2 f b (S n) = f undefined (foldrNat2 f b n) -- Arggh! undefined > > -- undefined is useful for prototyping, but its a real > -- problem for running code! > > -- Actually I had another problem as well... > -- > -- The difference between Nat and [a] is that List 'carries' some data > -- therefore (Nat -> b -> b) on Nat is not equivalent to (a -> b -> b) > -- on [a]. > > -- So rather than change the type signature first, get rid of the > -- undefined and see what happens > > foldrNat3 f b Z = b > foldrNat3 f b (S n) = f (foldrNat3 f b n) > > -- *GHCi> :t foldrNat3 > -- > (t -> t) -> t -> Nat -> t > > -- GHCi likes to call type variables t, but the signature is equal to > > -- foldrNat3 :: (b -> b) -> b -> Nat -> b > > > -- This looks promising - it typechecks! > -- So try a test: > > fromNat :: Nat -> Int > fromNat n = foldrNat3 (+1) 0 n > > demo1 = fromNat (S (S (S Z))) -- 3 ?? > > -- By experimenting we seem to have a good answer, > -- other people might prefer a more rigorous proof though. -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From daniel.is.fischer at web.de Thu Feb 4 16:05:18 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 4 15:39:27 2010 Subject: [Haskell-beginners] show vs. Data.ByteString.Char8.unpack for ByteString In-Reply-To: References: Message-ID: <201002042205.18578.daniel.is.fischer@web.de> Am Donnerstag 04 Februar 2010 21:46:39 schrieb Hong Yang: > Hi, > > What is the difference between show and unpack when the function > arguments are of ByteString type? I thought they are the same, but they > are not interchangeable at compile time. > > Thanks, > > Hong If you're using Data.ByteString, unpack has type ByteString -> [Word8] unpack and show are the same (perhaps excepting efficiency) if you use Data.ByteString.Char8 (ditto for Data.ByteString.Lazy[.Char8]). From mutilating.cauliflowers.stephen at blacksapphire.com Thu Feb 4 16:08:41 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Thu Feb 4 15:40:11 2010 Subject: [Haskell-beginners] show vs. Data.ByteString.Char8.unpack for ByteString In-Reply-To: References: Message-ID: <4B6B3759.1010309@blacksapphire.com> Hong, 'show' of a ByteString will put quotes around the text and lots of \ for escaping certain characters, whereas unpack will translate each byte one-to-one to a Char. Steve Hong Yang wrote: > Hi, > > What is the difference between show and unpack when the function > arguments are of ByteString type? I thought they are the same, but they > are not interchangeable at compile time. > > Thanks, > > Hong > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From patrick.leboutillier at gmail.com Thu Feb 4 17:14:33 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Feb 4 16:46:00 2010 Subject: [Haskell-beginners] Typeclass problems Message-ID: Hi all, I've written a small type class that is meant to behave a bit like Show: class Show a => Echo a where echo :: a -> String echoList :: [a] -> String echoListSep :: a -> String echo = show echoListSep _ = " " echoList [] = "" echoList [x] = echo x echoList (x:xs) = echo x ++ echoListSep x ++ echoList xs instance Echo Char where echo c = [c] echoListSep _ = "" instance Echo a => Echo [a] where echo = echoList instance Echo Int where instance Echo Integer where instance Echo Double where instance Echo Float where gen = map (const 1) f xs = map echo $ gen xs However the code doesn't compile on the last line. But it does compile if I replace 'echo' with 'show'. What's missing to make my typeclass behave like Show and accept input of any type (besides all the missing instances...)? I looked at the code for Show but I didn't see anything that looked "magical"... Thanks, Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From mutilating.cauliflowers.stephen at blacksapphire.com Thu Feb 4 17:30:32 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Thu Feb 4 17:02:03 2010 Subject: [Haskell-beginners] Typeclass problems In-Reply-To: References: Message-ID: <4B6B4A88.6000702@blacksapphire.com> Patrick, I fixed it by adding a type signature to this line: gen = map (const (1::Int)) The problem is that the literal '1' is of type Num t => t, which is never tied to a concrete type anywhere. It has to know the type definitely before it can decide which type class to use. Steve Patrick LeBoutillier wrote: > Hi all, > > I've written a small type class that is meant to behave a bit like Show: > > class Show a => Echo a where > echo :: a -> String > echoList :: [a] -> String > echoListSep :: a -> String > > echo = show > echoListSep _ = " " > > echoList [] = "" > echoList [x] = echo x > echoList (x:xs) = echo x ++ echoListSep x ++ echoList xs > > > instance Echo Char where > echo c = [c] > echoListSep _ = "" > > instance Echo a => Echo [a] where > echo = echoList > > instance Echo Int where > instance Echo Integer where > instance Echo Double where > instance Echo Float where > > > gen = map (const 1) > > f xs = map echo $ gen xs > > > However the code doesn't compile on the last line. > But it does compile if I replace 'echo' with 'show'. > What's missing to make my typeclass behave like Show and accept input > of any type (besides all the missing instances...)? > I looked at the code for Show but I didn't see anything that looked "magical"... > > > Thanks, > > Patrick > > From daniel.is.fischer at web.de Thu Feb 4 17:37:12 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 4 17:10:29 2010 Subject: [Haskell-beginners] Typeclass problems In-Reply-To: References: Message-ID: <201002042337.13045.daniel.is.fischer@web.de> Am Donnerstag 04 Februar 2010 23:14:33 schrieb Patrick LeBoutillier: > Hi all, > > I've written a small type class that is meant to behave a bit like Show: > > class Show a => Echo a where > echo :: a -> String > echoList :: [a] -> String > echoListSep :: a -> String > > echo = show > echoListSep _ = " " > > echoList [] = "" > echoList [x] = echo x > echoList (x:xs) = echo x ++ echoListSep x ++ echoList xs > > > instance Echo Char where > echo c = [c] > echoListSep _ = "" > > instance Echo a => Echo [a] where > echo = echoList > > instance Echo Int where > instance Echo Integer where > instance Echo Double where > instance Echo Float where > > > gen = map (const 1) > > f xs = map echo $ gen xs > > > However the code doesn't compile on the last line. > But it does compile if I replace 'echo' with 'show'. > What's missing to make my typeclass behave like Show and accept input > of any type (besides all the missing instances...)? > I looked at the code for Show but I didn't see anything that looked > "magical"... The "magic" is that Show is defined in the standard libraries. Read http://haskell.org/onlinereport/decls.html#sect4.3.4 In particular, the last bullet point of "In situations where an ambiguous type is discovered, an ambiguous type variable, v, is defaultable if: * v appears only in constraints of the form C v, where C is a class, and * at least one of these classes is a numeric class, (that is, Num or a subclass of Num), and * all of these classes are defined in the Prelude or a standard library (Figures 6.2--6.3, pages -- show the numeric classes, and Figure 6.1, page , shows the classes defined in the Prelude.) " Now, gen xs :: Num a => [a] And you want to map echo over it, so we get the constraint (Num a, Echo a). Echo is not defined in the standard libraries, thus no defaulting takes place, you have to specify the type of 1 explicitly, map echo (gen xs :: [Int]) should work. In real programmes, the type is often deducible from the context, so you'll be bitten by the defaulting restrictions less often then than at the ghci prompt. There's a proposal (or a couple) to change the defaulting rules in coming language standards, see e.g. http://hackage.haskell.org/trac/haskell- prime/wiki/Defaulting > > > Thanks, > > Patrick HTH, Daniel From rogerking915 at yahoo.com Fri Feb 5 00:37:23 2010 From: rogerking915 at yahoo.com (Roger King) Date: Fri Feb 5 00:08:46 2010 Subject: [Haskell-beginners] Simulation of interconnect network Message-ID: <352309.12509.qm@web57606.mail.re1.yahoo.com> I am building a simulator for an interconnect network for a multiprocessor computer. I would like to develop it in Haskell as an opportunity to learn Haskell. The network will have a number of routers with input ports and output ports and crossbars between them. I would like to simulate the protocol. This would be an event driven simulator. It would be at a high level, leaving out many details. I would like it to be fast and be able to run it on several processors. I would like to know if you have any advice. Has anyone done this before? Are there any discrete event simulators written in Haskell? R From haskell at utr.dk Fri Feb 5 04:42:03 2010 From: haskell at utr.dk (Ulrik Rasmussen) Date: Fri Feb 5 04:13:55 2010 Subject: [Haskell-beginners] Simulation of interconnect network In-Reply-To: <352309.12509.qm@web57606.mail.re1.yahoo.com> References: <352309.12509.qm@web57606.mail.re1.yahoo.com> Message-ID: <4B6BE7EB.3070306@utr.dk> Roger King skrev: > I am building a simulator for an interconnect network for a multiprocessor computer. I would like to develop it in Haskell as an opportunity to learn Haskell. > > The network will have a number of routers with input ports and output ports and crossbars between them. I would like to simulate the protocol. This would be an event driven simulator. It would be at a high level, leaving out many details. I would like it to be fast and be able to run it on several processors. > > I would like to know if you have any advice. Has anyone done this before? Are there any discrete event simulators written in Haskell? > R > (Resubmussion: Forgot to send the mail to the list) You could take a look at the CHP library: http://www.cs.kent.ac.uk/projects/ofa/chp/. The library is influenced by the CSP calculus, which is used to reason about systems of communicating processes. Using this, you could model each node of your network as a CHP process which communicates with the other nodes over channels. All the communication is synchronous, and the theory behind it is pretty solid: http://www.usingcsp.com/ /Ulrik From apfelmus at quantentunnel.de Fri Feb 5 05:54:29 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Fri Feb 5 05:29:18 2010 Subject: [Haskell-beginners] Re: Fast tree manipulation In-Reply-To: <22d241861002040434q471e6ebk2a77f3bc12ff9b5c@mail.gmail.com> References: <22d241861002040434q471e6ebk2a77f3bc12ff9b5c@mail.gmail.com> Message-ID: Gabi wrote: > I didn't see any mature zipper libraries to efficiently manipulate trees. > Can you point me to any mature libs ? There's http://hackage.haskell.org/package/rosezipper for Data.Tree and http://hackage.haskell.org/package/zipper for generic data types. Not sure if they count as "mature", but zippers are straightforward to implement anyway. You could even roll your own, it's very simple. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From dmorti at gmail.com Fri Feb 5 22:25:43 2010 From: dmorti at gmail.com (Duncan Mortimer) Date: Fri Feb 5 21:57:27 2010 Subject: [Haskell-beginners] Installing hmatrix on OS X Message-ID: Hi all, I'm trying to install the easyVision library on OS X, following the notes at http://mit.edu/harold/Public/easyVisionNotes.html. However, despite a few hours web trawling and hacking away with various cabal options, I can't get "hmatrix" to install. I'm using OS X 10.5.8 with GHC 6.10.4. I installed gsl using macports, as suggested in the notes above, but cabal doesn't seem to be able to find it. The error I'm getting is: [13:22:35 dmorti hmatrix-0.8.2.0]$ cabal install hmatrix Resolving dependencies... [1 of 1] Compiling Main ( /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/Setup.lhs, /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/Main.o ) Linking /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/setup ... Configuring hmatrix-0.8.2.0... Checking foreign libraries... FAIL *** Sorry, I can't link GSL. *** Please make sure that the appropriate -dev packages are installed. *** You can also specify the required libraries using *** cabal install hmatrix --configure-option=link:lib1,lib2,lib3,etc. setup: Package hmatrix-0.8.2.0 can't be built on this system. cabal: Error: some packages failed to install: hmatrix-0.8.2.0 failed during the building phase. The exception was: exit: ExitFailure 1 It appears that others have also had this error, but have been able to fix it up by including "--extra-lib-dirs" and "--extra-include-dirs" options, or using "ld-options: -framework vecLib". I've tried both of these approaches, but still get the same errors. Can anyone offer any suggestions? Thanks very much for your help, Duncan Mortimer From andy.elvey at paradise.net.nz Sat Feb 6 00:27:24 2010 From: andy.elvey at paradise.net.nz (Andy Elvey) Date: Fri Feb 5 23:58:48 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell Message-ID: <4B6CFDBC.7000403@paradise.net.nz> Hi all - I'm doing a public-domain package of "functional" programs" in C, and that involves trying to replicate (in C) a number of Haskell functions. The two that I'm looking at now are "pred" and "succ". I've seen the examples on zvon.org, which give "pred 5" as being 4, and "pred B" as being "A". Ok, that's fine, no problem. However, is my understanding correct that this can be extended to lists (arrays in C) so that (for example) for a list ["foo", "bar", "baz"] , "pred "bar" " would give you "foo" , and "succ "bar" " would give you "baz"? Thanks in advance - bye for now - - Andy From allbery at ece.cmu.edu Sat Feb 6 00:54:37 2010 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Feb 6 00:26:20 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell In-Reply-To: <4B6CFDBC.7000403@paradise.net.nz> References: <4B6CFDBC.7000403@paradise.net.nz> Message-ID: On Feb 6, 2010, at 00:27 , Andy Elvey wrote: > However, is my understanding correct that this can be extended to > lists (arrays in C) so that (for example) for a list ["foo", "bar", > "baz"] , "pred "bar" " would give you "foo" , and "succ "bar" " > would give you "baz"? No. Leaving aside that you don't manipulate lists that way in Haskell, "bar" is a random value of type String (which is [Char]), not a member of an enumeration. For comparison: > data MyType = Foo | Bar | Baz deriving Enum; > -- pred Bar = Foo, succ Bar = Baz Some languages (e.g. Perl) do give an enumerable value to Strings, but `succ "Bar"' would be something like "Baq". (This could be done in Haskell, with some pain; it starts with `instance (Enum a, Bounded a) => Enum [a] where...'.) You can't go from a string like "Bar" to whatever lists might contain that string (and what if multiple lists contained it?), so there's no way to get an interpretation like that; you would need an enumerator which had access both to the list and the member in question, whereas Enum has access only to the type. (There exist dependent type systems where you could encode that information into a defined (sub)type, but Haskell doesn't support it directly.) What you *can* do is that, because the types of list and array indexes are members of Enum, you can for example use Data.List.index to determine the index (if any!) of that item in your list, then take prev or succ of that. Beware of running off the end of the list, though. (It's also more complicated for arrays because array indexes are themselves defined by a typeclass `Ix'.) -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20100206/e33481eb/PGP.bin From andy.elvey at paradise.net.nz Sat Feb 6 01:31:49 2010 From: andy.elvey at paradise.net.nz (Andy Elvey) Date: Sat Feb 6 01:03:15 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell In-Reply-To: References: <4B6CFDBC.7000403@paradise.net.nz> Message-ID: <4B6D0CD5.4020906@paradise.net.nz> Brandon S. Allbery KF8NH wrote: > On Feb 6, 2010, at 00:27 , Andy Elvey wrote: >> However, is my understanding correct that this can be extended to >> lists (arrays in C) so that (for example) for a list ["foo", "bar", >> "baz"] , "pred "bar" " would give you "foo" , and "succ "bar" " >> would give you "baz"? > > > No. Leaving aside that you don't manipulate lists that way in > Haskell, "bar" is a random value of type String (which is [Char]), not > a member of an enumeration. For comparison: > > > data MyType = Foo | Bar | Baz deriving Enum; > > -- pred Bar = Foo, succ Bar = Baz > > Some languages (e.g. Perl) do give an enumerable value to Strings, but > `succ "Bar"' would be something like "Baq". (This could be done in > Haskell, with some pain; it starts with `instance (Enum a, Bounded a) > => Enum [a] where...'.) You can't go from a string like "Bar" to > whatever lists might contain that string (and what if multiple lists > contained it?), so there's no way to get an interpretation like that; > you would need an enumerator which had access both to the list and the > member in question, whereas Enum has access only to the type. (There > exist dependent type systems where you could encode that information > into a defined (sub)type, but Haskell doesn't support it directly.) > > What you *can* do is that, because the types of list and array indexes > are members of Enum, you can for example use Data.List.index to > determine the index (if any!) of that item in your list, then take > prev or succ of that. Beware of running off the end of the list, > though. (It's also more complicated for arrays because array indexes > are themselves defined by a typeclass `Ix'.) Hi Brandon - thanks very much for that! Ok. Yes, that is exactly what I was after. I was indeed thinking that "pred" and "succ" related to the "previous" and "next" elements in a list, but I now see that that is not the case. So, I may look at doing what I would call "lpred" and lsucc" - the predecessor and successor of a list element. I'm somewhat surprised that (from what I can tell) Haskell doesn't seem to have those two functions for a list. I may be wrong.... Anyway - thanks again. Bye for now - - Andy From allbery at ece.cmu.edu Sat Feb 6 01:45:58 2010 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Sat Feb 6 01:17:41 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell Message-ID: Andy Elvey wrote: > So, I may look at doing what I would call "lpred" and lsucc" - the > predecessor and successor of a list element. I'm somewhat surprised > that (from what I can tell) Haskell doesn't seem to have those two > functions for a list. I may be wrong.... Again, lists don't work that way; a list in Haskell is a single immutable object, you can pull items from it using (!!), head, etc., but you can't have a pointer into the "middle" of a list. You can have a sublist (for example, `tail ["foo", "bar", "baz"]' = `["bar", "baz"]') --- but you can't get from there to the "foo", as it isn't part of that new list. (This despite the fact that what `tail' gives you is going to be shared in actual storage with the original list. You don't have a backpointer into that original list to follow.) This is actually a feature of the Haskell model: it's usually easier to reason about these kinds of structures, where you can treat any operation as producing a new object and the Haskell compiler takes care of optimizations for you (shared representations, possibly recognizing that it can quietly do an update-in-place because you can't possibly reach the old value, etc.). You may want to take a look at the Seq type defined in the Data.Seq module, though; you have a `view' (what you can think of as a cursor) on a given Seq which can be moved back and forth. -- brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 195 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20100206/e705b3a9/PGP.bin From maydwell at gmail.com Sat Feb 6 03:52:19 2010 From: maydwell at gmail.com (Lyndon Maydwell) Date: Sat Feb 6 03:23:39 2010 Subject: [Haskell-beginners] Installing hmatrix on OS X In-Reply-To: References: Message-ID: I'm having a similar error when trying to install HMatrix on OS X as well. Interested if anyone can find a solution. On Sat, Feb 6, 2010 at 11:25 AM, Duncan Mortimer wrote: > Hi all, > > I'm trying to install the easyVision library on OS X, following the > notes at http://mit.edu/harold/Public/easyVisionNotes.html. > > However, despite a few hours web trawling and hacking away with > various cabal options, I can't get "hmatrix" to install. ?I'm using OS > X 10.5.8 with GHC 6.10.4. ? I installed gsl using macports, as > suggested in the notes above, but cabal doesn't seem to be able to > find it. ?The error I'm getting is: > > [13:22:35 dmorti hmatrix-0.8.2.0]$ cabal install hmatrix > Resolving dependencies... > [1 of 1] Compiling Main ? ? ? ? ? ? ( > /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/Setup.lhs, > /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/Main.o > ) > Linking /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/setup > ... > Configuring hmatrix-0.8.2.0... > Checking foreign libraries... FAIL > ?*** Sorry, I can't link GSL. > ?*** Please make sure that the appropriate -dev packages are installed. > ?*** You can also specify the required libraries using > ?*** cabal install hmatrix --configure-option=link:lib1,lib2,lib3,etc. > setup: Package hmatrix-0.8.2.0 can't be built on this system. > cabal: Error: some packages failed to install: > hmatrix-0.8.2.0 failed during the building phase. The exception was: > exit: ExitFailure 1 > > It appears that others have also had this error, but have been able to > fix it up by including "--extra-lib-dirs" and "--extra-include-dirs" > options, or using "ld-options: -framework vecLib". ?I've tried both of > these approaches, but still get the same errors. > > Can anyone offer any suggestions? > > Thanks very much for your help, > Duncan Mortimer > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From apfelmus at quantentunnel.de Sat Feb 6 05:34:43 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sat Feb 6 05:06:25 2010 Subject: [Haskell-beginners] Re: Installing hmatrix on OS X In-Reply-To: References: Message-ID: Duncan Mortimer wrote: > I'm trying to install the easyVision library on OS X, following the > notes at http://mit.edu/harold/Public/easyVisionNotes.html. > > However, despite a few hours web trawling and hacking away with > various cabal options, I can't get "hmatrix" to install. I'm using OS > X 10.5.8 with GHC 6.10.4. I installed gsl using macports, as > suggested in the notes above, but cabal doesn't seem to be able to > find it. The error I'm getting is: > > [13:22:35 dmorti hmatrix-0.8.2.0]$ cabal install hmatrix > Resolving dependencies... > [1 of 1] Compiling Main ( > /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/Setup.lhs, > /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/Main.o > ) > Linking /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/setup > .... > Configuring hmatrix-0.8.2.0... > Checking foreign libraries... FAIL > *** Sorry, I can't link GSL. > *** Please make sure that the appropriate -dev packages are installed. > *** You can also specify the required libraries using > *** cabal install hmatrix --configure-option=link:lib1,lib2,lib3,etc. > setup: Package hmatrix-0.8.2.0 can't be built on this system. > cabal: Error: some packages failed to install: > hmatrix-0.8.2.0 failed during the building phase. The exception was: > exit: ExitFailure 1 > > It appears that others have also had this error, but have been able to > fix it up by including "--extra-lib-dirs" and "--extra-include-dirs" > options, or using "ld-options: -framework vecLib". I've tried both of > these approaches, but still get the same errors. > > Can anyone offer any suggestions? hmatrix uses a custom configure script which I think is supposed to make live easier for Linux users. Unfortunately, it doesn't work on MacOS X; you have to deactivate it. If I remember correctly, you can do this with changing the build type to build-type: Simple in the cabal file. Then, add the relevant libraries extra-lib-dirs: /opt/local/lib/ extra-include-dirs: /opt/local/include/ extra-libraries: gsl framework: Accelerate -- or framework: vecLib for earlier versions of MacOS X and off you go. Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From apfelmus at quantentunnel.de Sat Feb 6 05:38:11 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sat Feb 6 05:11:24 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> Message-ID: Stephen Tetley wrote: > The parser has a type restricted return type - always a 'Hughes > string' with efficient concatenation (ShowS :: String -> String) > rather than some polymorphic answer (e.g a parse tree). For formatting > it allows you to add text without consuming any: > > inserttext :: String -> Parser > inserttext str = return (showString str) > > Or rewrite matched input: > > rewrite :: String -> String -> Parser > rewrite inp out = string inp >> return (showString out) > > Or drop text, I presume this is what the place combinator does. > > Its a nice technique. Ah, nice; thanks for the explanation! Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From felipe.lessa at gmail.com Sat Feb 6 06:02:31 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Feb 6 05:33:56 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell In-Reply-To: References: Message-ID: <20100206110231.GA29938@kira.casa> On Sat, Feb 06, 2010 at 01:45:58AM -0500, Brandon S. Allbery KF8NH wrote: > Andy Elvey wrote: > >So, I may look at doing what I would call "lpred" and lsucc" - the > >predecessor and successor of a list element. I'm somewhat > >surprised that (from what I can tell) Haskell doesn't seem to have > >those two functions for a list. I may be wrong.... > > Again, lists don't work that way; a list in Haskell is a single > immutable object, you can pull items from it using (!!), head, etc., > but you can't have a pointer into the "middle" of a list. You can > have a sublist (for example, `tail ["foo", "bar", "baz"]' = `["bar", > "baz"]') --- but you can't get from there to the "foo", as it isn't > part of that new list. (This despite the fact that what `tail' > gives you is going to be shared in actual storage with the original > list. You don't have a backpointer into that original list to > follow.) Although we can't have a pointer to the middle of a list [a], we can have another data struture that behaves sort of as if we had that pointer: a zipper. For example, http://hackage.haskell.org/packages/archive/ListZipper/1.1.1.0/doc/html/Data-List-Zipper.html To understand a list zipper you could think of it as something like struct zipper { list left, right; } So we track our "position" by tracking what's on the left and what's on the right. By using the API of the link above you could have something similar to what you wanted: lpred :: Zipper a -> a lpred = focus . left lsucc :: Zipper a -> a lsucc = focus . right -- Felipe. From deolivem at gmail.com Sat Feb 6 06:28:31 2010 From: deolivem at gmail.com (Marco De Oliveira) Date: Sat Feb 6 05:59:53 2010 Subject: [Haskell-beginners] How to initialize a C struct with FFI Message-ID: Hi, I try to initialize a C struct using the FFI API and ghc stays blocked when I execute my code (and I got sometimes the error "out of memory"). I do not understand, I do not find any mistake in my code: {-# OPTIONS -XTypeSynonymInstances #-} import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable type CStruct = (CULong, CULong) instance Storable CStruct where sizeOf _ = 2*sizeOf (undefined::CULong) alignment _ = alignment (undefined::CULong) test = alloca (\pStruct -> do poke pStruct ( (fromIntegral 1)::CULong, (fromIntegral 1)::CULong ) ) Thanks for your help. Marco -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100206/b94d5a8d/attachment.html From dmorti at gmail.com Sat Feb 6 07:26:38 2010 From: dmorti at gmail.com (Duncan Mortimer) Date: Sat Feb 6 06:58:19 2010 Subject: [Haskell-beginners] Installing hmatrix on OS X In-Reply-To: References: Message-ID: Hi All, Following Heinrich's advice (thanks), I found the following worked: in hmatrix.cabal: change "build-type: Custom" to "build-type: Simple" and at the end of hmatrix.cabal: change "extra-libraries:" to "extra-libraries: gsl" and "extra-lib-dirs: " to "extra-lib-dirs: /opt/local/lib/" Then at the command line run: cabal --extra-include-dirs=/opt/local/include configure followed by cabal --extra-include-dirs=/opt/local/include install I couldn't work out how to put the extra-include-dirs details into the hmatrix.cabal file --- I kept getting the error "Warning: hmatrix.cabal: Unknown fields: extra-include-dirs". Anyway --- the above appears to have worked for me. I thought I'd send it back to the list in the hopes that it helps someone else. And if anyone can explain where "extra-include-dirs" should go in the hmatrix.cabal file, please let me know! :) best, Duncan On Sat, Feb 6, 2010 at 6:52 PM, Lyndon Maydwell wrote: > I'm having a similar error when trying to install HMatrix on OS X as > well. Interested if anyone can find a solution. > > On Sat, Feb 6, 2010 at 11:25 AM, Duncan Mortimer wrote: >> Hi all, >> >> I'm trying to install the easyVision library on OS X, following the >> notes at http://mit.edu/harold/Public/easyVisionNotes.html. >> >> However, despite a few hours web trawling and hacking away with >> various cabal options, I can't get "hmatrix" to install. ?I'm using OS >> X 10.5.8 with GHC 6.10.4. ? I installed gsl using macports, as >> suggested in the notes above, but cabal doesn't seem to be able to >> find it. ?The error I'm getting is: >> >> [13:22:35 dmorti hmatrix-0.8.2.0]$ cabal install hmatrix >> Resolving dependencies... >> [1 of 1] Compiling Main ? ? ? ? ? ? ( >> /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/Setup.lhs, >> /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/Main.o >> ) >> Linking /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/setup >> ... >> Configuring hmatrix-0.8.2.0... >> Checking foreign libraries... FAIL >> ?*** Sorry, I can't link GSL. >> ?*** Please make sure that the appropriate -dev packages are installed. >> ?*** You can also specify the required libraries using >> ?*** cabal install hmatrix --configure-option=link:lib1,lib2,lib3,etc. >> setup: Package hmatrix-0.8.2.0 can't be built on this system. >> cabal: Error: some packages failed to install: >> hmatrix-0.8.2.0 failed during the building phase. The exception was: >> exit: ExitFailure 1 >> >> It appears that others have also had this error, but have been able to >> fix it up by including "--extra-lib-dirs" and "--extra-include-dirs" >> options, or using "ld-options: -framework vecLib". ?I've tried both of >> these approaches, but still get the same errors. >> >> Can anyone offer any suggestions? >> >> Thanks very much for your help, >> Duncan Mortimer >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > From dmorti at gmail.com Sat Feb 6 07:31:54 2010 From: dmorti at gmail.com (Duncan Mortimer) Date: Sat Feb 6 07:03:34 2010 Subject: [Haskell-beginners] Installing hmatrix on OS X In-Reply-To: References: Message-ID: Ooops. Cancel that --- I didn't get any errors on running "cabal install", and "hmatrix-0.8.2.0" is listed in my ghc-pkg list. However, on attempting to run the tests listed on: http://sites.google.com/site/wwwhmatrix/installation i.e.: (in ghci): > import Numeric.LinearAlgebra.Tests > runTests 20 I get the error: ... ... Loading package hmatrix-0.8.2.0 ... linking ... : unknown symbol `_zgemm_' ghc: unable to load package `hmatrix-0.8.2.0' Does anyone have any suggestions as to what's going on now? Thanks, Duncan On Sat, Feb 6, 2010 at 10:26 PM, Duncan Mortimer wrote: > Hi All, > > Following Heinrich's advice (thanks), I found the following worked: > > in hmatrix.cabal: > > change "build-type: Custom" to "build-type: Simple" > > and at the end of hmatrix.cabal: > > change "extra-libraries:" ? to ? "extra-libraries: gsl" > and > "extra-lib-dirs: " ?to ? "extra-lib-dirs: /opt/local/lib/" > > Then at the command line run: > > cabal --extra-include-dirs=/opt/local/include configure > > followed by > > cabal --extra-include-dirs=/opt/local/include install > > I couldn't work out how to put the extra-include-dirs details into the > hmatrix.cabal file --- I kept getting the error "Warning: > hmatrix.cabal: Unknown fields: extra-include-dirs". > > Anyway --- the above appears to have worked for me. ?I thought I'd > send it back to the list in the hopes that it helps someone else. ?And > if anyone can explain where "extra-include-dirs" should go in the > hmatrix.cabal file, please let me know! :) > > best, > Duncan > > > On Sat, Feb 6, 2010 at 6:52 PM, Lyndon Maydwell wrote: >> I'm having a similar error when trying to install HMatrix on OS X as >> well. Interested if anyone can find a solution. >> >> On Sat, Feb 6, 2010 at 11:25 AM, Duncan Mortimer wrote: >>> Hi all, >>> >>> I'm trying to install the easyVision library on OS X, following the >>> notes at http://mit.edu/harold/Public/easyVisionNotes.html. >>> >>> However, despite a few hours web trawling and hacking away with >>> various cabal options, I can't get "hmatrix" to install. ?I'm using OS >>> X 10.5.8 with GHC 6.10.4. ? I installed gsl using macports, as >>> suggested in the notes above, but cabal doesn't seem to be able to >>> find it. ?The error I'm getting is: >>> >>> [13:22:35 dmorti hmatrix-0.8.2.0]$ cabal install hmatrix >>> Resolving dependencies... >>> [1 of 1] Compiling Main ? ? ? ? ? ? ( >>> /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/Setup.lhs, >>> /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/Main.o >>> ) >>> Linking /var/folders/05/05Ltg9vxE+a1hR422nbuE++++TI/-Tmp-/hmatrix-0.8.2.05810/hmatrix-0.8.2.0/dist/setup/setup >>> ... >>> Configuring hmatrix-0.8.2.0... >>> Checking foreign libraries... FAIL >>> ?*** Sorry, I can't link GSL. >>> ?*** Please make sure that the appropriate -dev packages are installed. >>> ?*** You can also specify the required libraries using >>> ?*** cabal install hmatrix --configure-option=link:lib1,lib2,lib3,etc. >>> setup: Package hmatrix-0.8.2.0 can't be built on this system. >>> cabal: Error: some packages failed to install: >>> hmatrix-0.8.2.0 failed during the building phase. The exception was: >>> exit: ExitFailure 1 >>> >>> It appears that others have also had this error, but have been able to >>> fix it up by including "--extra-lib-dirs" and "--extra-include-dirs" >>> options, or using "ld-options: -framework vecLib". ?I've tried both of >>> these approaches, but still get the same errors. >>> >>> Can anyone offer any suggestions? >>> >>> Thanks very much for your help, >>> Duncan Mortimer >>> _______________________________________________ >>> Beginners mailing list >>> Beginners@haskell.org >>> http://www.haskell.org/mailman/listinfo/beginners >>> >> > From patrick.leboutillier at gmail.com Sat Feb 6 08:18:44 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Sat Feb 6 07:50:05 2010 Subject: [Haskell-beginners] Typeclass problems In-Reply-To: <201002042337.13045.daniel.is.fischer@web.de> References: <201002042337.13045.daniel.is.fischer@web.de> Message-ID: Daniel, Thanks a lot for the info! That's a subtlety I wasn't aware of. Patrick On Thu, Feb 4, 2010 at 5:37 PM, Daniel Fischer wrote: > Am Donnerstag 04 Februar 2010 23:14:33 schrieb Patrick LeBoutillier: >> Hi all, >> >> I've written a small type class that is meant to behave a bit like Show: >> >> class Show a => Echo a where >> ? echo :: a -> String >> ? echoList :: [a] -> String >> ? echoListSep :: a -> String >> >> ? echo = show >> ? echoListSep _ = " " >> >> ? echoList [] = "" >> ? echoList [x] = echo x >> ? echoList (x:xs) = echo x ++ echoListSep x ++ echoList xs >> >> >> instance Echo Char where >> ? echo c = [c] >> ? echoListSep _ = "" >> >> instance Echo a => Echo [a] where >> ? echo = echoList >> >> instance Echo Int where >> instance Echo Integer where >> instance Echo Double where >> instance Echo Float where >> >> >> gen = map (const 1) >> >> f xs = map echo $ gen xs >> >> >> However the code doesn't compile on the last line. >> But it does compile if I replace 'echo' with 'show'. >> What's missing to make my typeclass behave like Show and accept input >> of any type (besides all the missing instances...)? >> I looked at the code for Show but I didn't see anything that looked >> "magical"... > > The "magic" is that Show is defined in the standard libraries. > Read http://haskell.org/onlinereport/decls.html#sect4.3.4 > In particular, the last bullet point of > > "In situations where an ambiguous type is discovered, an ambiguous type > variable, v, is defaultable if: > > ? ?* v appears only in constraints of the form C v, where C is a class, > and > ? ?* at least one of these classes is a numeric class, (that is, Num or a > subclass of Num), and > ? ?* all of these classes are defined in the Prelude or a standard library > (Figures 6.2--6.3, pages -- show the numeric classes, and Figure 6.1, page > , shows the classes defined in the Prelude.) " > > > Now, > > gen xs :: Num a => [a] > > And you want to map echo over it, so we get the constraint > (Num a, Echo a). > > Echo is not defined in the standard libraries, thus no defaulting takes > place, you have to specify the type of 1 explicitly, > > map echo (gen xs :: [Int]) > > should work. > > In real programmes, the type is often deducible from the context, so you'll > be bitten by the defaulting restrictions less often then than at the ghci > prompt. > > There's a proposal (or a couple) to change the defaulting rules in coming > language standards, see e.g. http://hackage.haskell.org/trac/haskell- > prime/wiki/Defaulting > > >> >> >> Thanks, >> >> Patrick > > HTH, > Daniel > > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From dbayer at barnard.edu Thu Feb 4 08:23:58 2010 From: dbayer at barnard.edu (Dave Bayer) Date: Sat Feb 6 08:16:56 2010 Subject: [Haskell-beginners] Re: Monadic composition without throwing genericity under the bus? In-Reply-To: <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> References: <4987afcd.130c420a.134e.4097@mx.google.com> <19BF564D-0337-48C3-8996-8AA923998DBE@math.columbia.edu> <20090203141712.GA24679@seas.upenn.edu> <511E81D6-BC3F-46C8-8D15-62D190FF828E@math.columbia.edu> <5fdc56d71002040325w26df3922v7da498e8141f894f@mail.gmail.com> Message-ID: <1CC008C2-CBC1-43AE-9916-30649A88248E@barnard.edu> Thanks for all your answers. Yes, Stephen explains exactly what I'm doing. I had been using a literate preprocessor that could have been written in Basic, but didn't include heredocs. It was very short, but I wanted something more idiomatic, so I stared at everyone's parser tutorials, wondering about monadic -vs- applicative etc. etc. The twin irritations of do notation everywhere, and ++ everywhere, pushed me over the edge to try ShowS-valued monads, and I loved how the code looked. Normally I accept wrappers on everything as just how one does business in Haskell. As you say, to avoid undecidable type issues. Here I was struggling for days to make the code as lean as possible, and I could almost get away without wrappers. I've been following the migration convention of ASCII for historic Prelude, Unicode for generic version of same, so I didn't want to steal ? for this one purpose; it should be categorical composition. I like the answer that m ? (->) is simply something different, I shouldn't think of it as composition. I had been using ? for this, I'll probably go back to it. For a simple parser tutorial, or my immediate application of munging text e.g. literate preprocessor, ok to hardwire ShowS-valued monads. However, when one does have to break down and go into do notation (e.g. to implement my heredocs which steal the indentation from the closing EOF, and otherwise looks cleaner with multiple parsing passes), it might be slicker to use a general (a ? b) type in place of ShowS. In fact, I believe one could do anything other parsers do, this way, with the benefit of most expressions being composition not requiring do-notation. Anyhow, going further with monads returning (a ? b) required me to make my peace with this composition issue, so I thank each of you! I will write up a tutorial on this form of parsing when I submit my literate preprocessor to Cabal. On Feb 4, 2010, at 6:25 AM, Stephen Tetley wrote: > The parser has a type restricted return type - always a 'Hughes > string' with efficient concatenation (ShowS :: String -> String) > rather than some polymorphic answer (e.g a parse tree). For formatting > it allows you to add text without consuming any: > > inserttext :: String -> Parser > inserttext str = return (showString str) > > Or rewrite matched input: > > rewrite :: String -> String -> Parser > rewrite inp out = string inp >> return (showString out) > > Or drop text, I presume this is what the place combinator does. > > Its a nice technique. > > On 4 February 2010 10:46, Heinrich Apfelmus wrote: >> >> This looks intriguing! Can you elaborate on how this works? > From uzytkownik2 at gmail.com Sat Feb 6 13:58:10 2010 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sat Feb 6 13:29:47 2010 Subject: [Haskell-beginners] Re: How to initialize a C struct with FFI In-Reply-To: References: Message-ID: <1265482690.5402.9.camel@picard> On Sat, 2010-02-06 at 12:28 +0100, Marco De Oliveira wrote: > Hi, > > I try to initialize a C struct using the FFI API and ghc stays blocked > when I execute my code (and I got sometimes the error "out of > memory"). > I do not understand, I do not find any mistake in my code: > > {-# OPTIONS -XTypeSynonymInstances #-} > > import Foreign.C.Types > import Foreign.Marshal.Alloc > import Foreign.Ptr > import Foreign.Storable > It can be written as: import Foreign import Foreign.C > > type CStruct = (CULong, CULong) > I guess that you may want to use newtype or data rather then type to avoid clashes (and have just 98 + FFI): newtype CStruct = CStruct (CULong, CULong) data CStruct = CStruct CULong CULong > instance Storable CStruct where > sizeOf _ = 2*sizeOf (undefined::CULong) > alignment _ = alignment (undefined::CULong) > To begin with - where's peek and poke? > test = alloca (\pStruct -> do > poke pStruct ( (fromIntegral 1)::CULong, (fromIntegral > 1)::CULong ) > ) If you just do this at the beginning you may want to use with (notation as with newtype/data): with (CStruct (1, 1)) (\ptr -> ...) Also is main = test? > Thanks for your help. > > Marco Regards From andy.elvey at paradise.net.nz Sat Feb 6 15:45:14 2010 From: andy.elvey at paradise.net.nz (Andy Elvey) Date: Sat Feb 6 15:16:37 2010 Subject: [Haskell-beginners] Just clarifying the "pred" and "succ" functions in Haskell In-Reply-To: <20100206110231.GA29938@kira.casa> References: <20100206110231.GA29938@kira.casa> Message-ID: <4B6DD4DA.4080703@paradise.net.nz> Felipe Lessa wrote: (snip ) > > Although we can't have a pointer to the middle of a list [a], we > can have another data struture that behaves sort of as if we had > that pointer: a zipper. For example, > > http://hackage.haskell.org/packages/archive/ListZipper/1.1.1.0/doc/html/Data-List-Zipper.html > > To understand a list zipper you could think of it as something like > > struct zipper { > list left, right; > } > > So we track our "position" by tracking what's on the left and > what's on the right. By using the API of the link above you > could have something similar to what you wanted: > > lpred :: Zipper a -> a > lpred = focus . left > > lsucc :: Zipper a -> a > lsucc = focus . right > > -- > Felipe. > Hi Felipe - Thanks very much for that! That's very handy to know. I think that I'll base my lpred and lsucc on this approach. Bye for now - - Andy From deolivem at gmail.com Sat Feb 6 18:04:06 2010 From: deolivem at gmail.com (Marco De Oliveira) Date: Sat Feb 6 17:35:26 2010 Subject: [Haskell-beginners] Re: How to initialize a C struct with FFI In-Reply-To: <1265482690.5402.9.camel@picard> References: <1265482690.5402.9.camel@picard> Message-ID: Hi Maciej, Thanks to have take some time to read this code. I rewrite using your comments: import Foreign import Foreign.C data CStruct = CStruct (CULong, CULong) instance Storable CStruct where sizeOf _ = 2*sizeOf (undefined::CULong) alignment _ = alignment (undefined::CULong) test = with (CStruct (1,1)) (\ptr -> return ()) The class Storable does not need to make your own peek and poke method (the class provide a default implementation). But with, i have still the behavior when I try this code in ghci. Please, can you test this code and tell me why ghci stay blocked after executing the method test. BR Marco 2010/2/6 Maciej Piechotka > On Sat, 2010-02-06 at 12:28 +0100, Marco De Oliveira wrote: > > Hi, > > > > I try to initialize a C struct using the FFI API and ghc stays blocked > > when I execute my code (and I got sometimes the error "out of > > memory"). > > I do not understand, I do not find any mistake in my code: > > > > {-# OPTIONS -XTypeSynonymInstances #-} > > > > import Foreign.C.Types > > import Foreign.Marshal.Alloc > > import Foreign.Ptr > > import Foreign.Storable > > > > It can be written as: > import Foreign > import Foreign.C > > > > > type CStruct = (CULong, CULong) > > > > I guess that you may want to use newtype or data rather then type to > avoid clashes (and have just 98 + FFI): > > newtype CStruct = CStruct (CULong, CULong) > data CStruct = CStruct CULong CULong > > > instance Storable CStruct where > > sizeOf _ = 2*sizeOf (undefined::CULong) > > alignment _ = alignment (undefined::CULong) > > > > To begin with - where's peek and poke? > > > test = alloca (\pStruct -> do > > poke pStruct ( (fromIntegral 1)::CULong, (fromIntegral > > 1)::CULong ) > > ) > > If you just do this at the beginning you may want to use with (notation > as with newtype/data): > > with (CStruct (1, 1)) (\ptr -> ...) > > > Also is main = test? > > Thanks for your help. > > > > Marco > > Regards > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100206/03455403/attachment.html From uzytkownik2 at gmail.com Sat Feb 6 18:44:38 2010 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Sat Feb 6 18:16:14 2010 Subject: [Haskell-beginners] Re: Re: How to initialize a C struct with FFI In-Reply-To: References: <1265482690.5402.9.camel@picard> Message-ID: <1265499878.5402.47.camel@picard> On Sun, 2010-02-07 at 00:04 +0100, Marco De Oliveira wrote: > Hi Maciej, > > Thanks to have take some time to read this code. > > I rewrite using your comments: > > import Foreign > import Foreign.C > > data CStruct = CStruct (CULong, CULong) > Hmm. You combined both newtype and data. While technically it is correct you have now one level more for program to consider. > instance Storable CStruct where > sizeOf _ = 2*sizeOf (undefined::CULong) > alignment _ = alignment (undefined::CULong) > > test = with (CStruct (1,1)) (\ptr -> return ()) > > The class Storable does not need to make your own peek and poke method > (the class provide a default implementation). Not quite. It does in terms of peek/pokeElemOff. Which has in terms of peek/pokeByteOff which has implementation in terms of peek/poke itself. Therefore you have infinite recursion - poke calls pokeElemOff which calls pokeByteOff which calls poke etc. Even the documentation specifies this: "Minimal complete definition: sizeOf, alignment, one of peek, peekElemOff and peekByteOff, and one of poke, pokeElemOff and pokeByteOff."[1] Sorry - I forgot about this (I only noticed that something is missing). > But with, i have still the behavior when I try this code in ghci. > My other suggestions only caused to avoid extensions/have type safety and shorten the function respectively - they did not alter behaviour. Regards [1] http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Foreign-Storable.html#t%3AStorable From apfelmus at quantentunnel.de Sun Feb 7 05:40:19 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Sun Feb 7 05:12:02 2010 Subject: [Haskell-beginners] Re: Installing hmatrix on OS X In-Reply-To: References: Message-ID: Duncan Mortimer wrote: > Ooops. Cancel that --- I didn't get any errors on running "cabal > install", and "hmatrix-0.8.2.0" is listed in my ghc-pkg list. > However, on attempting to run the tests listed on: > > http://sites.google.com/site/wwwhmatrix/installation > > i.e.: (in ghci): > >> import Numeric.LinearAlgebra.Tests >> runTests 20 > > I get the error: > > .... > .... > Loading package hmatrix-0.8.2.0 ... linking ... : > unknown symbol `_zgemm_' > ghc: unable to load package `hmatrix-0.8.2.0' > > Does anyone have any suggestions as to what's going on now? Looks like you're missing a function from LAPACK. Did you add frameworks: Accelerate too? >> Anyway --- the above appears to have worked for me. I thought I'd >> send it back to the list in the hopes that it helps someone else. And >> if anyone can explain where "extra-include-dirs" should go in the >> hmatrix.cabal file, please let me know! :) My bad, the relevant field in the cabal file is called include-dirs: /opt/local/include Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From kane96 at gmx.de Sun Feb 7 15:03:00 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Feb 7 14:34:29 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <201002022239.08105.daniel.is.fischer@web.de> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> Message-ID: <20100207200300.25910@gmx.net> thanks so far. I used "getInt = fmap read getLine", because I think it's enough for me I have to do it for a more complex case of reading an own data type (myDatatype) with is deriving Show and return an error otherwise. I tried the following which didn't work: readMyDatatype :: IO myDatatype readMyDatatype = do if readLn == (show readLn) then return readLn else do error "input error" -------- Original-Nachricht -------- > Datum: Tue, 2 Feb 2010 22:39:07 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] define action getInt like getLine > Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: > > Hi, > > how can I write an action > > getInt :: IO Int > > that works like > > getLine :: IO String > > but for Int instead of String. I know that I can read the input with > > getLine and then convert it by using read, but don't know how to write > > it as an action. I tried getInt :: IO Int > > getInt read <- getLine > > but that doesn't work. > > There are many possibilities. > > The shortest is > > getInt :: IO Int > getInt = readLn > > another short and sweet is > > getInt :: IO Int > getInt = fmap read getLine -- or liftM read getLine > > But neither of these deals well with malformed input, if that's a > possibility to reckon with, use e.g. the reads function > > getInt :: IO Int > getInt = do > inp <- getLine > case reads inp of > ((a,tl):_) | all isSpace tl -> return a > _ -> handle malformed input -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From john.moore54 at gmail.com Sun Feb 7 15:14:17 2010 From: john.moore54 at gmail.com (John Moore) Date: Sun Feb 7 14:45:35 2010 Subject: [Haskell-beginners] defining expression Message-ID: <4f7ad1ad1002071214t471596f0p814d997b9f7c697a@mail.gmail.com> Hi, This gives me the explaination that it expecting a Expression but it been giving a IO b can some explain whats going on please. import Maybe data Expression = Val Double | Add Expression Expression | Subtract Expression Expression | Multiply Expression Expression | Divide Expression Expression | Var String | Let String Expression Expression deriving Show demo1 = (Add(Multiply(Divide(Subtract(Val 25)(Val 5))(Val 10))(Val 7))(Val 30)) type Dict =[(String,Expression)] emptyDict :: Dict emptyDict = [] addEntry :: String->Expression ->Dict -> Dict addEntry n e d = (n,e): d lookupEntry :: String -> Dict -> Maybe Expression lookupEntry n [] = Nothing lookupEntry n (x:xs) = if (n == k) then (Just v) else lookupEntry n xs where (k,v) = x evalStep :: Dict -> Expression -> Expression evalStep d(Val x)= (Val x) evalStep d(Add x y) = case x of (Val a) -> case y of (Val b) -> Val (a+b) left -> Add x (evalStep d y) right -> Add (evalStep d x)y evalStep d(Subtract x y) = case x of (Val a) -> case y of (Val b) -> Val (a-b) left -> Subtract x (evalStep d y) right -> Subtract (evalStep d x)y evalStep d(Multiply x y) = case x of (Val a) -> case y of (Val b) -> Val (a*b) left -> Multiply x (evalStep d y) right -> Multiply (evalStep d x)y evalStep d (Divide x y) = case x of (Val a) -> case y of (Val b) -> Val (a/b) left -> Divide x (evalStep d y) right -> Divide (evalStep d x)y evalStep d (Let n e1 e2) = do putStrLn ("Adding definition for "++n) v <- evalStep d (addEntry n e1 d) e2 putStrLn ("Removing definition for "++n) return v evaluate :: Dict-> [Expression] -> Expression -> IO () evaluate d(x:xs) e = do putStrLn (show e) putStrLn "Do another step (y/n) or rollback (r)? :" c <- getLine case c of "y" -> let e'= (evalStep d e)in evaluate d (e:x:xs) e'-- build up history "r" -> case (x:xs) of (x:xs)-> evaluate d xs x []-> do { putStrLn "Empty" ;evaluate d(x:xs) e } "n" -> putStrLn $ "Ok you said no :" ++ c John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100207/7a684da5/attachment-0001.html From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 7 15:25:13 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 7 14:56:37 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <20100207200300.25910@gmx.net> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> Message-ID: <4B6F21A9.1020702@blacksapphire.com> Hi there, Data types are required to start with a capital letter, so you'll have to call it MyDatatype. I can't see where readLn is defined. Can you paste a bit more of the code? I don't quite understand how your reading of your own data type is meant to work - normally you would use read or reads from the Read type class. A more subtle point - because of the way lazy evaluation works, it is generally better to use 'fail' rather than 'error' when in a monad. In some monads it's possible that 'error' may do nothing. Steve kane96@gmx.de wrote: > thanks so far. > I used "getInt = fmap read getLine", because I think it's enough for me > > I have to do it for a more complex case of reading an own data type (myDatatype) with is deriving Show and return an error otherwise. > I tried the following which didn't work: > > readMyDatatype :: IO myDatatype > readMyDatatype = do > if readLn == (show readLn) > then return readLn > else do error "input error" > > > -------- Original-Nachricht -------- >> Datum: Tue, 2 Feb 2010 22:39:07 +0100 >> Von: Daniel Fischer >> An: beginners@haskell.org >> CC: kane96@gmx.de >> Betreff: Re: [Haskell-beginners] define action getInt like getLine > >> Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: >>> Hi, >>> how can I write an action >>> getInt :: IO Int >>> that works like >>> getLine :: IO String >>> but for Int instead of String. I know that I can read the input with >>> getLine and then convert it by using read, but don't know how to write >>> it as an action. I tried getInt :: IO Int >>> getInt read <- getLine >>> but that doesn't work. >> There are many possibilities. >> >> The shortest is >> >> getInt :: IO Int >> getInt = readLn >> >> another short and sweet is >> >> getInt :: IO Int >> getInt = fmap read getLine -- or liftM read getLine >> >> But neither of these deals well with malformed input, if that's a >> possibility to reckon with, use e.g. the reads function >> >> getInt :: IO Int >> getInt = do >> inp <- getLine >> case reads inp of >> ((a,tl):_) | all isSpace tl -> return a >> _ -> handle malformed input > From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 7 15:43:26 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 7 15:14:50 2010 Subject: [Haskell-beginners] defining expression In-Reply-To: <4f7ad1ad1002071214t471596f0p814d997b9f7c697a@mail.gmail.com> References: <4f7ad1ad1002071214t471596f0p814d997b9f7c697a@mail.gmail.com> Message-ID: <4B6F25EE.9040706@blacksapphire.com> John, I'm seeing the error you describe "Couldn't match expected type `Expression' against inferred type `IO b'" on this line: evalStep d (Let n e1 e2) = do putStrLn ("Adding definition for "++n) <--- The trouble here is that evalStep's type is :: Dict -> Expression -> Expression, and Haskell doesn't allow general I/O in a function with a return type other than IO . This restrictiveness is pretty much the whole point of Haskell. You have two choices, either... 1. Change the type of evalStep to Dict -> Expression -> IO Expression, and of any function that calls it (and so on up the call chain), or 2. Use Debug.trace for your debug output, like this: trace ("adding/removing definition of "++n) $ evalStep d (addEntry n e1 d) e2 If you want 'adding' and 'removing definition of' as separate messages before and after (sequenced relative to other traces you might add), this is not straightforward, but it can be done. Essentially in pure Haskell code you have to think in terms of data dependency rather than sequence in time. Steve John Moore wrote: > Hi, > This gives me the explaination that it expecting a Expression but it > been giving a IO b can some explain whats going on please. > > import Maybe > data Expression = Val Double > | Add Expression Expression > | Subtract Expression Expression > | Multiply Expression Expression > | Divide Expression Expression > | Var String > | Let String Expression Expression > deriving Show > demo1 = (Add(Multiply(Divide(Subtract(Val 25)(Val 5))(Val 10))(Val > 7))(Val 30)) > type Dict =[(String,Expression)] > emptyDict :: Dict > emptyDict = [] > addEntry :: String->Expression ->Dict -> Dict > addEntry n e d = (n,e): d > lookupEntry :: String -> Dict -> Maybe Expression > lookupEntry n [] = Nothing > lookupEntry n (x:xs) = if (n == k) > then (Just v) > else lookupEntry n xs > where (k,v) = x > evalStep :: Dict -> Expression -> Expression > evalStep d(Val x)= (Val x) > > evalStep d(Add x y) > = case x of > (Val a) -> case y of > (Val b) -> Val (a+b) > left -> Add x (evalStep d y) > right -> Add (evalStep d x)y > evalStep d(Subtract x y) > = case x of > (Val a) -> case y of > (Val b) -> Val (a-b) > left -> Subtract x (evalStep d y) > right -> Subtract (evalStep d x)y > evalStep d(Multiply x y) > = case x of > (Val a) -> case y of > (Val b) -> Val (a*b) > left -> Multiply x (evalStep d y) > right -> Multiply (evalStep d x)y > evalStep d (Divide x y) > = case x of > (Val a) -> case y of > (Val b) -> Val (a/b) > left -> Divide x (evalStep d y) > right -> Divide (evalStep d x)y > evalStep d (Let n e1 e2) = do > putStrLn ("Adding definition for "++n) > v <- evalStep d (addEntry n e1 d) e2 > putStrLn ("Removing definition for "++n) > return v > > evaluate :: Dict-> [Expression] -> Expression -> IO () > evaluate d(x:xs) e = do > putStrLn (show e) > putStrLn "Do another step (y/n) or rollback (r)? :" > c <- getLine > case c of > "y" -> let e'= (evalStep d e)in evaluate d (e:x:xs) e'-- build up > history > > "r" -> case (x:xs) of > (x:xs)-> evaluate d xs x > []-> do { putStrLn "Empty" > ;evaluate d(x:xs) e > } > "n" -> putStrLn $ "Ok you said no :" ++ c > > > John > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From fox.joe87 at gmail.com Mon Feb 8 00:25:58 2010 From: fox.joe87 at gmail.com (Joe Fox) Date: Sun Feb 7 23:57:14 2010 Subject: [Haskell-beginners] Problems with System-Eval-Haskell Message-ID: <27e52ad11002072125y17dc6151sbe2204b45823216c@mail.gmail.com> Hi I am fairly new to haskell , I was trying to use Eval function in haskell but its giving me a problem , even the example code given in * http://www.cse.unsw.edu.au/~dons/hs-plugins/html/System-Eval-Haskell.html* do i <- eval "1 + 6 :: Int" [] :: IO (Maybe Int) when (isJust i) $ putStrLn (show (fromJust i)) is not working for me , it gives following error on the commandline: Warning: -Onot is deprecated: Use -O0 instead and doesnt print 7 , i guess that is what is expected to be printed. Can any one point me in the right way how to use eval function ? Thanks Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100207/56978857/attachment.html From daniel.schoepe at googlemail.com Mon Feb 8 13:20:11 2010 From: daniel.schoepe at googlemail.com (Daniel Schoepe) Date: Mon Feb 8 12:51:33 2010 Subject: [Haskell-beginners] Problems with System-Eval-Haskell In-Reply-To: <27e52ad11002072125y17dc6151sbe2204b45823216c@mail.gmail.com> References: <27e52ad11002072125y17dc6151sbe2204b45823216c@mail.gmail.com> Message-ID: <1265653083-sup-8800@nemesis.home> Excerpts from Joe Fox's message of Mon Feb 08 06:25:58 +0100 2010: > Hi > [..] > Can any one point me in the right way how to use eval function ? > > > Thanks > Joe I haven't used the module you mentioned but hint worked quite well for me when I needed a way to evaluate Haskell expressions at runtime: http://hackage.haskell.org/package/hint -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20100208/d2957862/signature.bin From kane96 at gmx.de Mon Feb 8 16:19:07 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Feb 8 15:50:46 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <4B6F21A9.1020702@blacksapphire.com> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> <4B6F21A9.1020702@blacksapphire.com> Message-ID: <20100208211907.106690@gmx.net> I want to read a "Month" from input and if this month issn't declared in my data type "Month" I want to throw an error message. data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) -------- Original-Nachricht -------- > Datum: Mon, 08 Feb 2010 09:25:13 +1300 > Von: "Stephen Blackheath [to Haskell-Beginners]" > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] define action getInt like getLine > Hi there, > > Data types are required to start with a capital letter, so you'll have > to call it MyDatatype. I can't see where readLn is defined. Can you > paste a bit more of the code? I don't quite understand how your reading > of your own data type is meant to work - normally you would use read or > reads from the Read type class. > > A more subtle point - because of the way lazy evaluation works, it is > generally better to use 'fail' rather than 'error' when in a monad. In > some monads it's possible that 'error' may do nothing. > > > Steve > > kane96@gmx.de wrote: > > thanks so far. > > I used "getInt = fmap read getLine", because I think it's enough for me > > > > I have to do it for a more complex case of reading an own data type > (myDatatype) with is deriving Show and return an error otherwise. > > I tried the following which didn't work: > > > > readMyDatatype :: IO myDatatype > > readMyDatatype = do > > if readLn == (show readLn) > > then return readLn > > else do error "input error" > > > > > > -------- Original-Nachricht -------- > >> Datum: Tue, 2 Feb 2010 22:39:07 +0100 > >> Von: Daniel Fischer > >> An: beginners@haskell.org > >> CC: kane96@gmx.de > >> Betreff: Re: [Haskell-beginners] define action getInt like getLine > > > >> Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: > >>> Hi, > >>> how can I write an action > >>> getInt :: IO Int > >>> that works like > >>> getLine :: IO String > >>> but for Int instead of String. I know that I can read the input with > >>> getLine and then convert it by using read, but don't know how to write > >>> it as an action. I tried getInt :: IO Int > >>> getInt read <- getLine > >>> but that doesn't work. > >> There are many possibilities. > >> > >> The shortest is > >> > >> getInt :: IO Int > >> getInt = readLn > >> > >> another short and sweet is > >> > >> getInt :: IO Int > >> getInt = fmap read getLine -- or liftM read getLine > >> > >> But neither of these deals well with malformed input, if that's a > >> possibility to reckon with, use e.g. the reads function > >> > >> getInt :: IO Int > >> getInt = do > >> inp <- getLine > >> case reads inp of > >> ((a,tl):_) | all isSpace tl -> return a > >> _ -> handle malformed input > > -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From stephen.tetley at gmail.com Mon Feb 8 16:27:42 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Mon Feb 8 15:58:55 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <20100208211907.106690@gmx.net> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> <4B6F21A9.1020702@blacksapphire.com> <20100208211907.106690@gmx.net> Message-ID: <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> Hello You can derive Read: > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show,Read) This will certainly throw an error on failure (might not be an error you would want to transmit to a user though), and it will only read "Jan" not "jan" or "January"... Plenty of good suggestions in this thread: http://www.haskell.org/pipermail/haskell-cafe/2010-January/072177.html Best wishes Stephen On 8 February 2010 21:19, wrote: > I want to read a "Month" from input and if this month issn't declared in my data type "Month" I want to throw an error message. > > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | Nov | Dec deriving (Eq,Enum,Show) > > > > -------- Original-Nachricht -------- >> Datum: Mon, 08 Feb 2010 09:25:13 +1300 >> Von: "Stephen Blackheath [to Haskell-Beginners]" >> An: kane96@gmx.de >> CC: beginners@haskell.org >> Betreff: Re: [Haskell-beginners] define action getInt like getLine > >> Hi there, >> >> Data types are required to start with a capital letter, so you'll have >> to call it MyDatatype. ?I can't see where readLn is defined. ?Can you >> paste a bit more of the code? ?I don't quite understand how your reading >> of your own data type is meant to work - normally you would use read or >> reads from the Read type class. >> >> A more subtle point - because of the way lazy evaluation works, it is >> generally better to use 'fail' rather than 'error' when in a monad. ?In >> some monads it's possible that 'error' may do nothing. >> >> >> Steve >> >> kane96@gmx.de wrote: >> > thanks so far. >> > I used "getInt = fmap read getLine", because I think it's enough for me >> > >> > I have to do it for a more complex case of reading an own data type >> (myDatatype) with is deriving Show and return an error otherwise. >> > I tried the following which didn't work: >> > >> > readMyDatatype :: IO myDatatype >> > readMyDatatype = do >> > ? if readLn == (show readLn) >> > ? then return readLn >> > ? else do error "input error" >> > >> > >> > -------- Original-Nachricht -------- >> >> Datum: Tue, 2 Feb 2010 22:39:07 +0100 >> >> Von: Daniel Fischer >> >> An: beginners@haskell.org >> >> CC: kane96@gmx.de >> >> Betreff: Re: [Haskell-beginners] define action getInt like getLine >> > >> >> Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: >> >>> Hi, >> >>> how can I write an action >> >>> getInt :: IO Int >> >>> that works like >> >>> getLine :: IO String >> >>> but for Int instead of String. I know that I can read the input with >> >>> getLine and then convert it by using read, but don't know how to write >> >>> it as an action. I tried getInt :: IO Int >> >>> getInt read <- getLine >> >>> but that doesn't work. >> >> There are many possibilities. >> >> >> >> The shortest is >> >> >> >> getInt :: IO Int >> >> getInt = readLn >> >> >> >> another short and sweet is >> >> >> >> getInt :: IO Int >> >> getInt = fmap read getLine ?-- or liftM read getLine >> >> >> >> But neither of these deals well with malformed input, if that's a >> >> possibility to reckon with, use e.g. the reads function >> >> >> >> getInt :: IO Int >> >> getInt = do >> >> ? ? inp <- getLine >> >> ? ? case reads inp of >> >> ? ? ? ((a,tl):_) | all isSpace tl -> return a >> >> ? ? ? _ -> handle malformed input >> > > > -- > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From kane96 at gmx.de Mon Feb 8 16:43:01 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Mon Feb 8 16:14:18 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> <4B6F21A9.1020702@blacksapphire.com> <20100208211907.106690@gmx.net> <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> Message-ID: <20100208214301.106720@gmx.net> but I have to write the action readMonth :: IO Month on my own and still don't have an idea how to do it -------- Original-Nachricht -------- > Datum: Mon, 8 Feb 2010 21:27:42 +0000 > Von: Stephen Tetley > An: > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] define action getInt like getLine > Hello > > You can derive Read: > > > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > Nov | Dec deriving (Eq,Enum,Show,Read) > > This will certainly throw an error on failure (might not be an error > you would want to transmit to a user though), and it will only read > "Jan" not "jan" or "January"... > > Plenty of good suggestions in this thread: > > http://www.haskell.org/pipermail/haskell-cafe/2010-January/072177.html > > > Best wishes > > Stephen > > On 8 February 2010 21:19, wrote: > > I want to read a "Month" from input and if this month issn't declared in > my data type "Month" I want to throw an error message. > > > > data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | > Nov | Dec deriving (Eq,Enum,Show) > > > > > > > > -------- Original-Nachricht -------- > >> Datum: Mon, 08 Feb 2010 09:25:13 +1300 > >> Von: "Stephen Blackheath [to Haskell-Beginners]" > > >> An: kane96@gmx.de > >> CC: beginners@haskell.org > >> Betreff: Re: [Haskell-beginners] define action getInt like getLine > > > >> Hi there, > >> > >> Data types are required to start with a capital letter, so you'll have > >> to call it MyDatatype. ?I can't see where readLn is defined. ?Can you > >> paste a bit more of the code? ?I don't quite understand how your > reading > >> of your own data type is meant to work - normally you would use read or > >> reads from the Read type class. > >> > >> A more subtle point - because of the way lazy evaluation works, it is > >> generally better to use 'fail' rather than 'error' when in a monad. > ?In > >> some monads it's possible that 'error' may do nothing. > >> > >> > >> Steve > >> > >> kane96@gmx.de wrote: > >> > thanks so far. > >> > I used "getInt = fmap read getLine", because I think it's enough for > me > >> > > >> > I have to do it for a more complex case of reading an own data type > >> (myDatatype) with is deriving Show and return an error otherwise. > >> > I tried the following which didn't work: > >> > > >> > readMyDatatype :: IO myDatatype > >> > readMyDatatype = do > >> > ? if readLn == (show readLn) > >> > ? then return readLn > >> > ? else do error "input error" > >> > > >> > > >> > -------- Original-Nachricht -------- > >> >> Datum: Tue, 2 Feb 2010 22:39:07 +0100 > >> >> Von: Daniel Fischer > >> >> An: beginners@haskell.org > >> >> CC: kane96@gmx.de > >> >> Betreff: Re: [Haskell-beginners] define action getInt like getLine > >> > > >> >> Am Dienstag 02 Februar 2010 22:20:03 schrieb kane96@gmx.de: > >> >>> Hi, > >> >>> how can I write an action > >> >>> getInt :: IO Int > >> >>> that works like > >> >>> getLine :: IO String > >> >>> but for Int instead of String. I know that I can read the input > with > >> >>> getLine and then convert it by using read, but don't know how to > write > >> >>> it as an action. I tried getInt :: IO Int > >> >>> getInt read <- getLine > >> >>> but that doesn't work. > >> >> There are many possibilities. > >> >> > >> >> The shortest is > >> >> > >> >> getInt :: IO Int > >> >> getInt = readLn > >> >> > >> >> another short and sweet is > >> >> > >> >> getInt :: IO Int > >> >> getInt = fmap read getLine ?-- or liftM read getLine > >> >> > >> >> But neither of these deals well with malformed input, if that's a > >> >> possibility to reckon with, use e.g. the reads function > >> >> > >> >> getInt :: IO Int > >> >> getInt = do > >> >> ? ? inp <- getLine > >> >> ? ? case reads inp of > >> >> ? ? ? ((a,tl):_) | all isSpace tl -> return a > >> >> ? ? ? _ -> handle malformed input > >> > > > > > -- > > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Mon Feb 8 16:58:56 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 8 16:32:02 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <20100208214301.106720@gmx.net> References: <20100202212003.55050@gmx.net> <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> <20100208214301.106720@gmx.net> Message-ID: <201002082258.56400.daniel.is.fischer@web.de> Am Montag 08 Februar 2010 22:43:01 schrieb kane96@gmx.de: > but I have to write the action > readMonth :: IO Month > on my own and still don't have an idea how to do it Go take a look at http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Prelude.html#v%3Aread http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Prelude.html#v%3AreadLn http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Prelude.html#v%3AgetLine The documentation should help you. From e at xtendo.org Tue Feb 9 02:40:57 2010 From: e at xtendo.org (han) Date: Tue Feb 9 02:12:08 2010 Subject: [Haskell-beginners] (Integral b, RealFrac b) to Int Message-ID: <5b4dd2a11002082340u254f2d44x3290102ea958e25b@mail.gmail.com> I have this code: line (sx, sy) (tx, ty) | abs (sx - tx) > abs (sy - ty) = zip xs [(sy + (sy - ty) * x / xd) | x <- [0 .. xd]] | otherwise = zip [(sx + (sx - tx) * y / yd) | y <- [0 .. yd]] ys where xs = target sx tx ys = target sy ty xd = abs (sx - tx) yd = abs (sy - ty) It currently has the inferred type signature of (Integral b, RealFrac b) => (b, b) -> (b, b) -> [(b, b)] and I want it to be (Int, Int) -> (Int, Int) -> [(Int, Int)] which, when coerced, causes an error. Any idea? From e at xtendo.org Tue Feb 9 02:53:13 2010 From: e at xtendo.org (han) Date: Tue Feb 9 02:24:25 2010 Subject: [Haskell-beginners] Re: (Integral b, RealFrac b) to Int In-Reply-To: <5b4dd2a11002082340u254f2d44x3290102ea958e25b@mail.gmail.com> References: <5b4dd2a11002082340u254f2d44x3290102ea958e25b@mail.gmail.com> Message-ID: <5b4dd2a11002082353w1671d5f2i572cbd4ea741142f@mail.gmail.com> I made a mistake in copying the original code. The correct version is: line (sx, sy) (tx, ty) | abs (sx - tx) > abs (sy - ty) = zip xs [round (sy + (sy - ty) * x / xd) | x <- [0 .. xd]] | otherwise = zip [round (sx + (sx - tx) * y / yd) | y <- [0 .. yd]] ys where xs = target sx tx ys = target sy ty xd = abs (sx - tx) yd = abs (sy - ty) On Tue, Feb 9, 2010 at 4:40 PM, han wrote: > I have this code: > > line (sx, sy) (tx, ty) > ? ? ? ?| abs (sx - tx) > abs (sy - ty) = > ? ? ? ? ? ? ? ?zip xs [(sy + (sy - ty) * x / xd) | x <- [0 .. xd]] > ? ? ? ?| otherwise = > ? ? ? ? ? ? ? ?zip [(sx + (sx - tx) * y / yd) | y <- [0 .. yd]] ys > ? ? ? ?where > ? ? ? ? ? ? ? ?xs = target sx tx > ? ? ? ? ? ? ? ?ys = target sy ty > ? ? ? ? ? ? ? ?xd = abs (sx - tx) > ? ? ? ? ? ? ? ?yd = abs (sy - ty) > > It currently has the inferred type signature of > > (Integral b, RealFrac b) => (b, b) -> (b, b) -> [(b, b)] > > and I want it to be > > (Int, Int) -> (Int, Int) -> [(Int, Int)] > > which, when coerced, causes an error. > > Any idea? > From dav.vire+haskell at gmail.com Tue Feb 9 02:59:21 2010 From: dav.vire+haskell at gmail.com (David Virebayre) Date: Tue Feb 9 02:30:34 2010 Subject: [Haskell-beginners] Re: (Integral b, RealFrac b) to Int In-Reply-To: <5b4dd2a11002082353w1671d5f2i572cbd4ea741142f@mail.gmail.com> References: <5b4dd2a11002082340u254f2d44x3290102ea958e25b@mail.gmail.com> <5b4dd2a11002082353w1671d5f2i572cbd4ea741142f@mail.gmail.com> Message-ID: <4c88418c1002082359l307ba182u656db3742531499e@mail.gmail.com> Start by replacing / by `div` David. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100209/03773cd5/attachment.html From legajid at free.fr Tue Feb 9 05:53:00 2010 From: legajid at free.fr (legajid@free.fr) Date: Tue Feb 9 05:24:18 2010 Subject: [Haskell-beginners] Filtering lists Message-ID: <67097985.20958731265712780646.JavaMail.root@zimbra10-e2.priv.proxad.net> Hi, i get a .csv file with two different record formats (too bad). The first one, identified by a "A" in the second field, contains 4 fields. The second one, identified by a "B", contains 10 fields. In order to put them in lists, i use lines then break to get a list of lists. Then i want to filter this list, one for the A list, the other one for the B list. Unfortunately, the pattern for the A type contains 4 fields; when a type B list occurs (10 fields), i get a message concerning the pattern : Non-exhaustive patterns in lambda How can i separate the two record formats? Thanks, Didier From Christian.Maeder at dfki.de Tue Feb 9 06:49:49 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Tue Feb 9 06:21:03 2010 Subject: [Haskell-beginners] Re: define action getInt like getLine In-Reply-To: <20100208214301.106720@gmx.net> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> <4B6F21A9.1020702@blacksapphire.com> <20100208211907.106690@gmx.net> <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> <20100208214301.106720@gmx.net> Message-ID: <4B714BDD.7060404@dfki.de> kane96@gmx.de schrieb: > but I have to write the action > readMonth :: IO Month > on my own and still don't have an idea how to do it Your idea (below) to use show on all possible values and compare it to the input line isn't that bad. >> On 8 February 2010 21:19, wrote: >>> I want to read a "Month" from input and if this month issn't declared in >> my data type "Month" I want to throw an error message. >>> data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Ago | Sep | Oct | >> Nov | Dec deriving (Eq,Enum,Show) The Enum class allows you to create the list of all possible values [Jan .. Dec] This list can be turn into a lookup-list (for Data.List.lookup) by map (\ a -> (show a, a)) >>>>> readMyDatatype = do >>>>> if readLn == (show readLn) >>>>> then return readLn >>>>> else do error "input error" This code is unfortunate, because "readLn" is an IO-Action (that cannot be compared or shown). Even if you insert as first line: readLn <- getLine readLn is a String that will never be equal to "show readLn", because show would add the double quotes. Also this shadowing of "readLn" is no good practise and should be avoided, so better use: str <- getLine and use the string "str" to look it up in the list above. Later on you may generalize readMonth to: readMyDatatype :: (Show a, Enum a, Bounded a) => IO a and also trim leading and trailing white space and case differences. Cheers Christian P.S. The functions read, readIO and readLn all have disadvantages in case of errors. In the spirit of readIO it is possible to program readMaybe, readEither or readM that are far more useful and missed very often. Many such variants are somewhere, but one of readMaybe, readEither or readM should be in a standard library. readM would not be a generalization of readIO! But readIO could be expressed using readM. From daniel.is.fischer at web.de Tue Feb 9 07:23:50 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 9 06:56:56 2010 Subject: [Haskell-beginners] Re: (Integral b, RealFrac b) to Int In-Reply-To: <5b4dd2a11002082353w1671d5f2i572cbd4ea741142f@mail.gmail.com> References: <5b4dd2a11002082340u254f2d44x3290102ea958e25b@mail.gmail.com> <5b4dd2a11002082353w1671d5f2i572cbd4ea741142f@mail.gmail.com> Message-ID: <201002091323.50903.daniel.is.fischer@web.de> Am Dienstag 09 Februar 2010 08:53:13 schrieb han: > I made a mistake in copying the original code. > > The correct version is: > > line (sx, sy) (tx, ty) > > | abs (sx - tx) > abs (sy - ty) = > > zip xs [round (sy + (sy - ty) * x / xd) | x <- [0 .. xd]] > > | otherwise = > > zip [round (sx + (sx - tx) * y / yd) | y <- [0 .. yd]] ys > where > xs = target sx tx > ys = target sy ty > xd = abs (sx - tx) > yd = abs (sy - ty) The type of (/) is Prelude> :t (/) (/) :: (Fractional a) => a -> a -> a and that of round Prelude> :t round round :: (RealFrac a, Integral b) => a -> b So the expression (sy + (sy - ty) * x / xd) forces sy, ty and xd to have the same Fractional type, fr. Since xd = abs (sx-tx), sx and tx have the same type. Now you apply round to that expression, which can give you any Integral type you desire. In the first branch, round (...) becomes the second component of the result pairs, in the second branch the first component. Probably target has type target :: (Num/Integral/? a) => a -> a -> [a] , which forces all types to be the same, giving the overall type line :: (Integral b, RealFrac b) => (b, b) -> (b, b) -> [(b, b)] Usually, no type is an instance of Integral and RealFrac at the same time, so it's not a usable function. You want the type line :: (Int,Int) -> (Int,Int) -> [(Int,Int)] One way to find out what went wrong is to give that type signature in the source and see what error message you get. It will probably be No instance for (Fractional Int) arising from a use of `/' at (source location) Possible fix: add an instance declaration for (Fractional Int) In the expression: ... So you can't divide Ints with (/). You can either use the integral division "div": (sy + (sy - ty) * x `div` xd), or, if the round is important and you can't use integral division - which gives floor -, convert the arguments to (/) to a Fractional type before dividing: (sy + round (fromIntegral ((sy - ty) * x) / fromIntegral xd)) > > On Tue, Feb 9, 2010 at 4:40 PM, han wrote: > > I have this code: > > > > line (sx, sy) (tx, ty) > > ? ? ? ?| abs (sx - tx) > abs (sy - ty) = > > ? ? ? ? ? ? ? ?zip xs [(sy + (sy - ty) * x / xd) | x <- [0 .. xd]] > > ? ? ? ?| otherwise = > > ? ? ? ? ? ? ? ?zip [(sx + (sx - tx) * y / yd) | y <- [0 .. yd]] ys > > ? ? ? ?where > > ? ? ? ? ? ? ? ?xs = target sx tx > > ? ? ? ? ? ? ? ?ys = target sy ty > > ? ? ? ? ? ? ? ?xd = abs (sx - tx) > > ? ? ? ? ? ? ? ?yd = abs (sy - ty) > > > > It currently has the inferred type signature of > > > > (Integral b, RealFrac b) => (b, b) -> (b, b) -> [(b, b)] > > > > and I want it to be > > > > (Int, Int) -> (Int, Int) -> [(Int, Int)] > > > > which, when coerced, causes an error. > > > > Any idea? From stephen.tetley at gmail.com Tue Feb 9 07:27:50 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Tue Feb 9 06:59:02 2010 Subject: [Haskell-beginners] Filtering lists In-Reply-To: <67097985.20958731265712780646.JavaMail.root@zimbra10-e2.priv.proxad.net> References: <67097985.20958731265712780646.JavaMail.root@zimbra10-e2.priv.proxad.net> Message-ID: <5fdc56d71002090427k1c912667y4237ef64d9bec335@mail.gmail.com> Hello If you have a list of String for each record, use partition from Data.List, e.g.: import Data.List ( partition ) partitionBySize :: [[String]] -> ([[String]],[[String]]) partitionBySize = partition (\xs -> length xs < 10) -- for demo-ing: printShortsLongs :: ([[String]],[[String]]) -> IO () printShortsLongs (xs,ys) = do putStrLn "Shorts:" mapM_ print xs putStrLn "Longs:" mapM_ print ys demo1 = printShortsLongs $ partitionBySize [ ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] , ["1", "2", "3", "4"] , ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] , ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] , ["1", "2", "3", "4"] ] On 9 February 2010 10:53, wrote: > Hi, > i get a .csv file with two different record formats (too bad). > The first one, identified by a "A" in the second field, contains 4 fields. > The second one, identified by a "B", contains 10 fields. > > In order to put them in lists, i use lines then break to get a list of lists. > Then i want to filter this list, one for the A list, the other one for the B list. > Unfortunately, the ?pattern for the A type contains 4 fields; when a type B list occurs (10 fields), i get a message concerning the pattern : Non-exhaustive patterns in lambda > > How can i separate the two record formats? > > Thanks, > Didier > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Tue Feb 9 07:35:54 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 9 07:08:59 2010 Subject: [Haskell-beginners] Filtering lists In-Reply-To: <67097985.20958731265712780646.JavaMail.root@zimbra10-e2.priv.proxad.net> References: <67097985.20958731265712780646.JavaMail.root@zimbra10-e2.priv.proxad.net> Message-ID: <201002091335.54997.daniel.is.fischer@web.de> Am Dienstag 09 Februar 2010 11:53:00 schrieb legajid@free.fr: > Hi, > i get a .csv file with two different record formats (too bad). > The first one, identified by a "A" in the second field, Couldn't that at least be the first field? > contains 4 fields. The second one, identified by a "B", > contains 10 fields. > > In order to put them in lists, i use lines then break to get a list of > lists. Then i want to filter this list, one for the A list, the other > one for the B list. Unfortunately, the pattern for the A type contains > 4 fields; when a type B list occurs (10 fields), i get a message > concerning the pattern : Non-exhaustive patterns in lambda > > How can i separate the two record formats? data Rec = A a1 a2 a3 a4 | B b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 deriving (whatever) isA :: Rec -> Bool isA (A _ _ _ _) = True isA _ = False breakIntoFields :: String -> [[String]] breakIntoFields file = map (splitOn ',') $ lines file recordToRec :: [String] -> Rec recordToRec (a1 : "A" : a2 : a3 : : a4 []) = (A (read a1) (read a2) (read a3) (read a4)) recordToRec (b1 : "B" : ... ) = (B (read b1) ...) recordToRec _ = error "invalid record format" records :: String -> [Rec] records = map recordToRec . breakIntoFields solution = Data.List.partition isA . records > > Thanks, > Didier From edgar.klerks at gmail.com Tue Feb 9 15:11:55 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Tue Feb 9 14:43:08 2010 Subject: [Haskell-beginners] Simplifying code Message-ID: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> Hi All, I wrote a program which permutates a list words with some rules. For example if I feed it a list like: banana waterloo vraag It gives back the list: banana b@nana ban@na b@n@na banan@ b@nan@ ban@n@ b@n@n@ waterloo wa+erloo water|oo waterl0o etc However I have the feeling I am doing things to complicated. I am still a beginner. Would someone like to help me simplify somethings. If you think this is inappropriate please state also. I am not offended then. I understand you are offering your spare time to help me. The first thing I don't get is this. I recognize some things could be rewritten with a bind operator (because of the concat $ fmap), but I am puzzled how: mutateWords :: [Char] -> [[Char]] mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> let char = snd x nm = number word lst = fst x in (insertAt char nm <$> lst) : z ) [[]] $ mw word ) Here is the full code: import Data.List import System import System.IO import Control.Applicative ---CONFIG section leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', 'a' ==> '@', 'v' ==> '^'] leata = fst.unzip $ leat leatb = snd.unzip $ leat -- Perl like assoc lists infixl 1 ==> a ==> b = (a, b) -- Flipped fmap sometimes nicer infixl 4 <$$> xs <$$> f = f <$> xs -- first I need to find the positions of the mutatable charachters. findPositions :: [Char] -> [[Int]] findPositions xs = take (length index) $ index <*> [xs] where index = elemIndices <$> leata -- And generate all subsequences findSubSeq :: [Char] -> [[[Int]]] findSubSeq = fmap subsequences <$> findPositions -- Only change elements which needs to be changed insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)] insertAt c xs ps = xs <$$> (\x -> if (fst x) `elem` ps then (fst x , c) else x ) -- Couples character to mutable positions mw word = (findSubSeq word) `zip` leatb number = zip [0..] mutateWords :: [Char] -> [[Char]] mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> let char = snd x nm = number word lst = fst x in (insertAt char nm <$> lst) : z ) [[]] $ mw word ) generateAll :: [Char] -> [[Char]] generateAll word = g lea $ mutateWords word where g 0 words = words g n words = g (n - 1) (nub $ words >>= mutateWords ) lea = length leata main = do filename <- getArgs wordlist <- readFile $ filename !! 0 let a = (words wordlist) >>= generateAll mapM_ putStrLn a -- Flatliner ICT Service, Email: Edgar.klerks@gmail.com, Tel: +31727851429 Fax: +31848363080 Skype: edgar.klerks Website: flatlinerict.nl Adres: Koelmalaan 258, 1813JD, Alkmaar Nederland -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100209/363c8357/attachment-0001.html From patrick.leboutillier at gmail.com Tue Feb 9 16:05:36 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Tue Feb 9 15:36:49 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> Message-ID: Hi, I think that this is a case where you have to let the recursion do the work for you. Here is a solution, although it seems it generates the permutations in a different order than yours: import Data.Maybe leet = [('s', '$'), ('t', '+'), ('l', '|'), ('o', '0'), ('e', '3'), ('a', '@'), ('v', '^')] mutateWords :: [String] -> [[String]] mutateWords = map mutateWord mutateWord :: String -> [String] mutateWord [] = [[]] mutateWord (c:cs) = concat . map perms $ mutateWord cs where perms cs' = map (: cs') $ mutateLetter c -- Returns a list of possible characters for c mutateLetter :: Char -> [Char] mutateLetter c = c : (maybeToList $ lookup c leet) Basically, in mutateLetter you generate a list of possible letters. For a char that stays the same, we return [c]. For a char that has a substitution in the leet list, we return [c, c']. Then in mutateWord we process the first letter, generate all the choices and prepend them to all the choices for the rest of the word. Patrick On Tue, Feb 9, 2010 at 3:11 PM, edgar klerks wrote: > Hi All, > > I wrote a program which permutates a list words with some rules. For example > if I feed it a list like: > > banana > waterloo > vraag > > It gives back the list: > > banana > b@nana > ban@na > b@n@na > banan@ > b@nan@ > ban@n@ > b@n@n@ > waterloo > wa+erloo > water|oo > waterl0o > etc > > However I have the feeling I am doing things to complicated. I am still a > beginner. Would someone like to help me simplify somethings. If you think > this is inappropriate please state also. I am not offended then. I > understand you are offering your spare time to help me. > > The first thing I don't get is this. I recognize some things could be > rewritten with a bind operator (because of the concat $ fmap), but I am > puzzled how: > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> > ??????????????????????? let char = snd x > ??????????????????????????? nm = number word > ??????????????????????????? lst = fst x > ??????????????????????? in (insertAt char nm <$> lst) : z > ??????????????? ) [[]] $ mw word ) > > > > > Here is the full code: > > > import Data.List > import System > import System.IO > import Control.Applicative > > > ---CONFIG section > > leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', 'a' > ==> '@', 'v' ==> '^'] > > leata = fst.unzip $ leat > leatb = snd.unzip $ leat > > -- Perl like assoc lists > infixl 1 ==> > a ==> b = (a, b) > > > -- Flipped fmap sometimes nicer > infixl 4 <$$> > > xs <$$> f = f <$> xs > > > -- first I need to find? the positions of the mutatable charachters. > findPositions :: [Char] -> [[Int]] > findPositions xs = take (length index) $ index <*> [xs] > ??????? where index = elemIndices <$> leata > > -- And generate all subsequences > findSubSeq :: [Char] -> [[[Int]]] > findSubSeq? = fmap subsequences <$> findPositions > > > -- Only change elements which needs to be changed > insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)] > insertAt c xs ps = xs <$$> (\x -> > ??????????????? if (fst x) `elem` ps > ??????????????????????? then (fst x , c) > ??????????????????????? else x > ??????????????? ) > -- Couples character to mutable positions > mw word = (findSubSeq word) `zip` leatb > > number = zip [0..] > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> > ??????????????????????? let char = snd x > ??????????????????????????? nm = number word > ??????????????????????????? lst = fst x > ??????????????????????? in (insertAt char nm <$> lst) : z > ??????????????? ) [[]] $ mw word ) > > generateAll :: [Char] -> [[Char]] > generateAll word = g lea $ mutateWords word > ??? where?? g 0 words = words > ??????????????? g n words = g (n - 1) (nub? $? words >>= mutateWords ) > ??????????????? lea = length leata > main = do > ??????? filename <- getArgs > ??????? wordlist <- readFile $ filename !! 0 > ??????? let a = (words wordlist) >>= generateAll > ??????? mapM_ putStrLn? a > > -- > Flatliner ICT Service, > Email: Edgar.klerks@gmail.com, > Tel: +31727851429 > Fax: +31848363080 > Skype: edgar.klerks > Website: flatlinerict.nl > Adres: Koelmalaan 258, > 1813JD, Alkmaar > Nederland > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From gtener at gmail.com Tue Feb 9 16:17:49 2010 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Tue Feb 9 15:48:59 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> Message-ID: <220e47b41002091317i3c16fe65i896764627874653e@mail.gmail.com> Hi A few remarks about your code: 1. 'String' is a type synonym for [Char]. It makes types like [[Char]] more readable (at least for me). 2. There is something imperative in the way you code: I think you rely too much on numbers as iterators. You don't have to use numbers to drive the program control flow. Examples: main = do filename <- getArgs wordlist <- readFile $ filename !! 0 Why not: main = do (filename:_) <- getArgs wordlist <- readFile filename Or: main = do filename <- head <$> getArgs wordlist <- readFile filename Another example: generateAll :: String -> [String] generateAll word = g lea $ mutateWords word where g 0 words = words g n words = g (n - 1) (nub $ words >>= mutateWords ) lea = length leata The 'g' function can be rewritten to get rid of the index number. Here is what I got: -- https://mail.google.com/mail/#inbox/126b45c29341640f import System.Environment ( getArgs ) import Control.Applicative ( (<$>) ) import Data.Set (Set) import qualified Data.Set as Set ---CONFIG section type Rule = (Char,Char) infixl 1 ==> a ==> b = (a, b) rules :: [Rule] rules = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0', 'e' ==> '3', 'a' ==> '@', 'v' ==> '^'] nubOrd :: (Ord a) => [a] -> [a] nubOrd = Set.toList . Set.fromList singleton x = [x] -- CORE PART -- we mutate all words, rule at a time. If we run out of rules, we finish. mutateWords :: [Rule] -> String -> [String] mutateWords rules word = foldr (\r acc -> nubOrd (concatMap (applyRule r) acc)) (singleton word) rules -- apply one rule to one word. the result is a list of words. applyRule :: Rule -> String -> [String] applyRule (old,new) wrd = aux wrd where aux [] = [[]] -- we may or may not apply our rule here. aux (c:cs) | c == old = [ c':suf | suf <- aux cs, c' <- [old,new] ] | otherwise = [ c :suf | suf <- aux cs ] main = do (filename:_) <- getArgs wordlist <- words <$> readFile filename let mutated = concatMap (mutateWords rules) wordlist mapM_ putStrLn mutated Best regards Krzysztof Skrz?tnicki On Tue, Feb 9, 2010 at 21:11, edgar klerks wrote: > Hi All, > > I wrote a program which permutates a list words with some rules. For example > if I feed it a list like: > > banana > waterloo > vraag > > It gives back the list: > > banana > b@nana > ban@na > b@n@na > banan@ > b@nan@ > ban@n@ > b@n@n@ > waterloo > wa+erloo > water|oo > waterl0o > etc > > However I have the feeling I am doing things to complicated. I am still a > beginner. Would someone like to help me simplify somethings. If you think > this is inappropriate please state also. I am not offended then. I > understand you are offering your spare time to help me. > > The first thing I don't get is this. I recognize some things could be > rewritten with a bind operator (because of the concat $ fmap), but I am > puzzled how: > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> > ??????????????????????? let char = snd x > ??????????????????????????? nm = number word > ??????????????????????????? lst = fst x > ??????????????????????? in (insertAt char nm <$> lst) : z > ??????????????? ) [[]] $ mw word ) > > > > > Here is the full code: > > > import Data.List > import System > import System.IO > import Control.Applicative > > > ---CONFIG section > > leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', 'a' > ==> '@', 'v' ==> '^'] > > leata = fst.unzip $ leat > leatb = snd.unzip $ leat > > -- Perl like assoc lists > infixl 1 ==> > a ==> b = (a, b) > > > -- Flipped fmap sometimes nicer > infixl 4 <$$> > > xs <$$> f = f <$> xs > > > -- first I need to find? the positions of the mutatable charachters. > findPositions :: [Char] -> [[Int]] > findPositions xs = take (length index) $ index <*> [xs] > ??????? where index = elemIndices <$> leata > > -- And generate all subsequences > findSubSeq :: [Char] -> [[[Int]]] > findSubSeq? = fmap subsequences <$> findPositions > > > -- Only change elements which needs to be changed > insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)] > insertAt c xs ps = xs <$$> (\x -> > ??????????????? if (fst x) `elem` ps > ??????????????????????? then (fst x , c) > ??????????????????????? else x > ??????????????? ) > -- Couples character to mutable positions > mw word = (findSubSeq word) `zip` leatb > > number = zip [0..] > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z -> > ??????????????????????? let char = snd x > ??????????????????????????? nm = number word > ??????????????????????????? lst = fst x > ??????????????????????? in (insertAt char nm <$> lst) : z > ??????????????? ) [[]] $ mw word ) > > generateAll :: [Char] -> [[Char]] > generateAll word = g lea $ mutateWords word > ??? where?? g 0 words = words > ??????????????? g n words = g (n - 1) (nub? $? words >>= mutateWords ) > ??????????????? lea = length leata > main = do > ??????? filename <- getArgs > ??????? wordlist <- readFile $ filename !! 0 > ??????? let a = (words wordlist) >>= generateAll > ??????? mapM_ putStrLn? a > > -- > Flatliner ICT Service, > Email: Edgar.klerks@gmail.com, > Tel: +31727851429 > Fax: +31848363080 > Skype: edgar.klerks > Website: flatlinerict.nl > Adres: Koelmalaan 258, > 1813JD, Alkmaar > Nederland > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From kane96 at gmx.de Tue Feb 9 16:41:11 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Tue Feb 9 16:12:28 2010 Subject: [Haskell-beginners] define action getInt like getLine In-Reply-To: <5fdc56d71002081426n55a78abfi8673a656629820c5@mail.gmail.com> References: <20100202212003.55050@gmx.net> <201002022239.08105.daniel.is.fischer@web.de> <20100207200300.25910@gmx.net> <4B6F21A9.1020702@blacksapphire.com> <20100208211907.106690@gmx.net> <5fdc56d71002081327q43fb78bcy40d2e4358b7a9d73@mail.gmail.com> <20100208214301.106720@gmx.net> <5fdc56d71002081426n55a78abfi8673a656629820c5@mail.gmail.com> Message-ID: <20100209214111.62680@gmx.net> ahhh, I didn't know that it's so simple with read :) -------- Original-Nachricht -------- > Datum: Mon, 8 Feb 2010 22:26:59 +0000 > Von: Stephen Tetley > An: kane96@gmx.de > Betreff: Re: [Haskell-beginners] define action getInt like getLine > Hello > > Upthread Daniel Fisher posted this one > > getInt :: IO Int > getInt = fmap read getLine > > If you check the type of read > > *GHCi> :t read > read :: (Read a) => String -> a > > 'reads' is polymorphic it will read anything from a String - well > within reason, anything that is an instance of the Read type class. > The "(Read a) => " part of the type signature indicates this > constraint - that "a" ( the return type of the function read) must be > an instance of Read. > > As I wrote, you can easily derive an instance of Read by adding Read > to the deriving clause of your data type, so the next thing to do is > write a function swapping as few parts from Daniel's example as > possible: > > -- Here you have to make a change as you want a Month rather than an > Int, so swap the ??? for what you want... > getMonth :: IO ??? > > -- The function definition can stay the same - none of the components > in Daniel's definition actually depended on reading an Int: > getMonth = fmap read getLine > > > > On 8 February 2010 21:43, wrote: > > but I have to write the action > > readMonth :: IO Month > > on my own and still don't have an idea how to do it > > > > -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Tue Feb 9 16:49:18 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 9 16:22:22 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> Message-ID: <201002092249.18970.daniel.is.fischer@web.de> Am Dienstag 09 Februar 2010 21:11:55 schrieb edgar klerks: > Hi All, > > I wrote a program which permutates a list words with some rules. For > example if I feed it a list like: > > banana > waterloo > vraag > > It gives back the list: > > banana > b@nana > ban@na > b@n@na > banan@ > b@nan@ > ban@n@ > b@n@n@ > waterloo > wa+erloo > water|oo > waterl0o > etc > > However I have the feeling I am doing things to complicated. I am still > a beginner. Would someone like to help me simplify somethings. Sure. If you don't mind that the mutations come in a different order, one thing that works wonders is "sequence", sequence :: Monad m => [m a] -> m [a] In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what sequence does, we can write import Control.Monad (sequence) generateAll :: String -> [String] generateAll word = sequence (map f word) where f c = case lookup c leat of Just r -> [c,r] Nothing -> [c] For each letter in the word, we generate the list of all possible substitutions (map f), "woot" ~> [['w'],['o','0'],['o','0'],['t','+']] and then sequence them, choosing each combination of substitutions once. A little more efficient than sequence is generateAll :: String -> [String] generateAll word = allCombs (map f word) where f c = case lookup c leat of Just r -> [c,r] Nothing -> [c] allCombs :: [[a]] -> [[a]] allCombs (l:ls) = [h:t | t <- allCombs ls, h <- l] allCombs [] = [[]] -- sequence (l:ls) = [h:t | h <- l, t <- sequence ls] -- with the generators in reverse order, cf. -- http://www.haskell.org/pipermail/haskell-cafe/2009-December/070149.html > If you think this is inappropriate please state also. How could it be? This list is for helping people understand Haskell better, exactly what you're after. > I am not offended then. I understand you are offering your > spare time to help me. If one thinks one's time isn't worth it, one can just ignore the post. > > The first thing I don't get is this. I recognize some things could be > rewritten with a bind operator (because of the concat $ fmap), but I am > puzzled how: > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z > -> > > let char = snd x > nm = number word > lst = fst x > in (insertAt char nm <$> lst) : z > ) [[]] $ mw word ) > > > > > Here is the full code: > > > import Data.List > import System > import System.IO > import Control.Applicative > > > ---CONFIG section > > leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', > 'a' ==> '@', 'v' ==> '^'] > > leata = fst.unzip $ leat leata = map fst leat leatb = map snd leat > leatb = snd.unzip $ leat > > -- Perl like assoc lists > infixl 1 ==> > a ==> b = (a, b) > > > -- Flipped fmap sometimes nicer > infixl 4 <$$> > > xs <$$> f = f <$> xs > > > -- first I need to find the positions of the mutatable charachters. No, you don't need to do that, it's in general more efficient to not care about positions when dealing with lists. > findPositions :: [Char] -> [[Int]] > findPositions xs = take (length index) $ index <*> [xs] > where index = elemIndices <$> leata [f1, ..., fm] <*> [x1, ..., xn] produces a list of length m*n, so length (index <*> [xs]) == length index * length [xs] == length index ~> remove "take (length index) $" > > -- And generate all subsequences > findSubSeq :: [Char] -> [[[Int]]] > findSubSeq = fmap subsequences <$> findPositions > > > -- Only change elements which needs to be changed > insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)] > insertAt c xs ps = xs <$$> (\x -> > if (fst x) `elem` ps > then (fst x , c) > else x > ) > -- Couples character to mutable positions > mw word = (findSubSeq word) `zip` leatb > > number = zip [0..] > > mutateWords :: [Char] -> [[Char]] > mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z > -> > > let char = snd x > nm = number word > lst = fst x > in (insertAt char nm <$> lst) : z > ) [[]] $ mw word ) Okay, I give up, that's too complicated :) One general remark. When you have an Ord instance, "nub" is an extremely bad idea (unless your lists are really short), as it's quadratic in the length of the list. map head . group . sort or import Data.Set toList . fromList are much better [O(l * log l) where l = length xs] > > generateAll :: [Char] -> [[Char]] > generateAll word = g lea $ mutateWords word > where g 0 words = words > g n words = g (n - 1) (nub $ words >>= mutateWords ) > lea = length leata > main = do > filename <- getArgs > wordlist <- readFile $ filename !! 0 > let a = (words wordlist) >>= generateAll > mapM_ putStrLn a From patrick.leboutillier at gmail.com Tue Feb 9 17:07:55 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Tue Feb 9 16:39:07 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <201002092249.18970.daniel.is.fischer@web.de> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002092249.18970.daniel.is.fischer@web.de> Message-ID: Daniel, > Sure. If you don't mind that the mutations come in a different order, one > thing that works wonders is "sequence", > > sequence :: Monad m => [m a] -> m [a] > > In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what > sequence does, we can write > > import Control.Monad (sequence) > > generateAll :: String -> [String] > generateAll word = sequence (map f word) > where > f c = case lookup c leat of > Just r -> [c,r] > Nothing -> [c] That's very nice! One question though: In the docs sequence is described as: "Evaluate each action in the sequence from left to right, and collect the results." How is one supposed to deduce what the behavior will be for the list monad (besides looking at the source)? Patrick -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From edgar.klerks at gmail.com Tue Feb 9 17:19:02 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Tue Feb 9 16:50:12 2010 Subject: [Haskell-beginners] Simplifying code Message-ID: <7c40819c1002091419q776a3552i155cf26c145ad2a2@mail.gmail.com> Thanks for all your examples. These are helping me really much. I have an imperative background (which hinders me), but I have the feeling functional programming has the future and I find it really fun to do. I will produce my own real functional version tomorrow and post it (maybe the day after that). It is 1:00 so i got to go to bed. Thanks for all your help! (If this message is not placed under the thread can someone explain how I do this from firefox. I have made my default mail handler gmail in firefox, but many times the post doesn't appear under the thread. I understand this is an annoyance.) With kind regards, Edgar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100209/58c4b021/attachment.html From e at xtendo.org Tue Feb 9 17:55:13 2010 From: e at xtendo.org (han) Date: Tue Feb 9 17:26:22 2010 Subject: [Haskell-beginners] Reading pixels in Haskell SDL Message-ID: <5b4dd2a11002091455n61c4467i592cf00a95396521@mail.gmail.com> I'm using SDL (http://hackage.haskell.org/packages/archive/SDL/0.5.9/doc/html/Graphics-UI-SDL.html) As far as I know, in the original SDL for C, reading and writing pixels on a surface is done by accessing pointer + y * width + x. In Pygame, since Python has no such thing as pointer, they have get_at and set_at function for this task. I thought there would be something equivalent in Haskell SDL, but couldn't find any. For writing pixels on the Surface, I've found a couple of functions: Graphics.UI.SDL.Video.fillRect (http://hackage.haskell.org/packages/archive/SDL/0.5.9/doc/html/Graphics-UI-SDL-Video.html#v%3AfillRect) Graphics.UI.SDL.Primitives.pixel (http://hackage.haskell.org/packages/archive/SDL-gfx/0.5.3/doc/html/Graphics-UI-SDL-Primitives.html#v%3Apixel) ... However, I can't find one that reads. Graphics.UI.SDL.Types.surfaceGetPixels (http://hackage.haskell.org/packages/archive/SDL/0.5.9/doc/html/Graphics-UI-SDL-Types.html#v%3AsurfaceGetPixels) looks like the one, but I have no idea how I can use it, since it returns Pixels which is defined as: data PixelsData type Pixels = Ptr PixelsData I want to read a pixel at (x, y) of a Surface. Does anyone know how? From daniel.is.fischer at web.de Tue Feb 9 18:31:07 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Feb 9 18:04:09 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002092249.18970.daniel.is.fischer@web.de> Message-ID: <201002100031.07292.daniel.is.fischer@web.de> Am Dienstag 09 Februar 2010 23:07:55 schrieb Patrick LeBoutillier: > Daniel, > > > Sure. If you don't mind that the mutations come in a different order, > > one thing that works wonders is "sequence", > > > > sequence :: Monad m => [m a] -> m [a] > > > > In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing > > what sequence does, we can write > > > > import Control.Monad (sequence) > > > > generateAll :: String -> [String] > > generateAll word = sequence (map f word) > > where > > f c = case lookup c leat of > > Just r -> [c,r] > > Nothing -> [c] > > That's very nice! Thanks. But from a clean-code-higher-level perspective, it's even nicer with your > -- Returns a list of possible characters for c > mutateLetter :: Char -> [Char] > mutateLetter c = c : (maybeToList $ lookup c leet) (here is a point where it would be even nicer if lookup had the type lookup :: (Eq a, MonadPlus m) => a -> [(a,b)] -> m b ). The performance-junkie in me would want to look at the core to make sure the maybeToList is eliminated by the compiler, though. > > One question though: In the docs sequence is described as: > > "Evaluate each action in the sequence from left to right, and > collect the results." > > How is one supposed to deduce what the behavior will be for the list > monad (besides looking at the source)? Given its polymorphic type sequence :: Monad m => [m a] -> m [a] , what can sequence do? For sequence [] , there's really only one possibility (not involving undefined/error), so sequence [] = return [] Okay, that was the trivial part, now what can be done with nonempty lists? It could ignore the input and return [] in any case, but that wouldn't be useful at all, so we can discard that possibility. What could be usefully done with sequence (m1:ms) ? It has to do something with m1 and something with ms, then combine the results to a list of [a], which it returns. What can it do with m1? Since all that sequence knows about m1 is the type (Monad m => m a), it can't do anything but what's provided by that constraint. Basically, it can only put it on the left of a (>>=). There's on decision to be made, shall it be sequence (m1:ms) = m1 >>= \x -> something with x and ms or something with ms >>= \xs -> (m1 >>= \x -> something with x and xs) ? And what can it do with the tail of the list, ms? Why, sequence it of course. So it's either sequence (m1:ms) = m1 >>= \x -> (sequence ms >>= \xs -> return (fun x xs)) {- sequence (m1:ms) = do x <- m1 xs <- sequence ms return (fun x xs) -} or sequence (m1:ms) = sequence ms >>= \xs -> (m1 >>= \x -> return (fun x xs)) {- sequence (m1:ms) = do xs <- sequence ms x <- m1 return (fun x xs) -} where fun :: forall a. a -> [a] -> [a] Now there's a lot of nonsense you could use for 'fun', fun x xs = reverse (x:xs) fun x xs = x:xs ++ [x,x,x] fun x xs = front ++ x:back where (front,back) = splitAt 17 xs ... , but the most prominent function of type forall a. a -> [a] -> [a] is the only one to be reasonably expected here, so fun x xs = x : xs and the only question that remains is in which order things are chained. That is answered by the docs, left to right, so sequence [] = return [] sequence (m1:ms) = m1 >>= \x -> sequence ms >>= \xs -> return (x:xs) {- sequence (m1:ms) = do x <- m1 xs <- sequence ms return (x:xs) sequence (m1:ms) = m1 >>= \x -> liftM (x :) (sequence ms) -} (or equivalent). Now you need to know how (>>=) is defined for [], namely ys >>= f = concatMap f ys. The short answer is, you can't deduce it wihout knowing the Monad instance for [], and if you know that well enough to not be confused by "evaluate the action" (which takes time), it's fairly straightforward. > > > Patrick From patrick.leboutillier at gmail.com Tue Feb 9 21:35:45 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Tue Feb 9 21:06:56 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <201002100031.07292.daniel.is.fischer@web.de> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002092249.18970.daniel.is.fischer@web.de> <201002100031.07292.daniel.is.fischer@web.de> Message-ID: Daniel, As usual, thanks a lot for this enlightening response. Patrick On Tue, Feb 9, 2010 at 6:31 PM, Daniel Fischer wrote: > Am Dienstag 09 Februar 2010 23:07:55 schrieb Patrick LeBoutillier: >> Daniel, >> >> > Sure. If you don't mind that the mutations come in a different order, >> > one thing that works wonders is "sequence", >> > >> > sequence :: Monad m => [m a] -> m [a] >> > >> > In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing >> > what sequence does, we can write >> > >> > import Control.Monad (sequence) >> > >> > generateAll :: String -> [String] >> > generateAll word = sequence (map f word) >> > ? ? where >> > ? ? f c = case lookup c leat of >> > ? ? ? ? ? ? ? ?Just r ?-> [c,r] >> > ? ? ? ? ? ? ? ?Nothing -> [c] >> >> That's very nice! > > Thanks. But from a clean-code-higher-level perspective, it's even nicer > with your > >> -- Returns a list of possible characters for c >> mutateLetter :: Char -> [Char] >> mutateLetter c = c : (maybeToList $ lookup c leet) > > (here is a point where it would be even nicer if lookup had the type > > lookup :: (Eq a, MonadPlus m) => a -> [(a,b)] -> m b > ). The performance-junkie in me would want to look at the core to make sure > the maybeToList is eliminated by the compiler, though. > >> >> One question though: In the docs sequence is described as: >> >> ? "Evaluate each action in the sequence from left to right, and >> collect the results." >> >> How is one supposed to deduce what the behavior will be for the list >> monad (besides looking at the source)? > > Given its polymorphic type > > sequence :: Monad m => [m a] -> m [a] > > , what can sequence do? > > For > sequence [] > , there's really only one possibility (not involving undefined/error), so > sequence [] = return [] > > Okay, that was the trivial part, now what can be done with nonempty lists? > It could ignore the input and return [] in any case, but that wouldn't be > useful at all, so we can discard that possibility. What could be usefully > done with > > sequence (m1:ms) ? > > It has to do something with m1 and something with ms, then combine the > results to a list of [a], which it returns. > What can it do with m1? Since all that sequence knows about m1 is the type > (Monad m => m a), it can't do anything but what's provided by that > constraint. Basically, it can only put it on the left of a (>>=). There's > on decision to be made, shall it be > > sequence (m1:ms) = m1 >>= \x -> something with x and ms > > or > > something with ms >>= \xs -> (m1 >>= \x -> something with x and xs) > ? > And what can it do with the tail of the list, ms? Why, sequence it of > course. > So it's either > > sequence (m1:ms) = m1 >>= \x -> (sequence ms >>= \xs -> return (fun x xs)) > {- > sequence (m1:ms) = do > ? ?x <- m1 > ? ?xs <- sequence ms > ? ?return (fun x xs) > -} > or > > sequence (m1:ms) = sequence ms >>= \xs -> (m1 >>= \x -> return (fun x xs)) > {- > sequence (m1:ms) = do > ? ?xs <- sequence ms > ? ?x <- m1 > ? ?return (fun x xs) > -} > > where > > fun :: forall a. a -> [a] -> [a] > > Now there's a lot of nonsense you could use for 'fun', > > fun x xs = reverse (x:xs) > fun x xs = x:xs ++ [x,x,x] > fun x xs = front ++ x:back where (front,back) = splitAt 17 xs > ... > , but the most prominent function of type forall a. a -> [a] -> [a] is the > only one to be reasonably expected here, so > > fun x xs = x : xs > > and the only question that remains is in which order things are chained. > That is answered by the docs, left to right, so > > sequence [] = return [] > sequence (m1:ms) = m1 >>= \x -> sequence ms >>= \xs -> return (x:xs) > {- > sequence (m1:ms) = do > ? ?x <- m1 > ? ?xs <- sequence ms > ? ?return (x:xs) > > sequence (m1:ms) = m1 >>= \x -> liftM (x :) (sequence ms) > -} > (or equivalent). > Now you need to know how (>>=) is defined for [], namely > > ys >>= f = concatMap f ys. > > The short answer is, you can't deduce it wihout knowing the Monad instance > for [], and if you know that well enough to not be confused by "evaluate > the action" (which takes time), it's fairly straightforward. > >> >> >> Patrick > > -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From es at ertes.de Tue Feb 9 21:41:20 2010 From: es at ertes.de (Ertugrul Soeylemez) Date: Tue Feb 9 21:12:54 2010 Subject: [Haskell-beginners] Re: Simplifying code References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002092249.18970.daniel.is.fischer@web.de> Message-ID: <20100210034120.6d7b9bac@tritium.streitmacht.eu> Patrick LeBoutillier wrote: > > Sure. If you don't mind that the mutations come in a different > > order, one thing that works wonders is "sequence", > > > > sequence :: Monad m => [m a] -> m [a] > > > > In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what > > sequence does, we can write > > > > import Control.Monad (sequence) > > > > generateAll :: String -> [String] > > generateAll word = sequence (map f word) > > where > > f c = case lookup c leat of > > Just r -> [c,r] > > Nothing -> [c] > > That's very nice! > > One question though: In the docs sequence is described as: > > "Evaluate each action in the sequence from left to right, and > collect the results." > > How is one supposed to deduce what the behavior will be for the list > monad (besides looking at the source)? Intuitively it's very easy to understand and makes perfect sense, if you interpret the list monad as nondeterminism: sequence [c1,c2,c3] = do x1 <- c1 x2 <- c2 x3 <- c3 return [x1,x2,x3] sequence ["ab", "cd", "ef"] = do x1 <- "ab" x2 <- "cd" x3 <- "ef" return [x1,x2,x3] = ["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"] In this code x1 stands for all results of c1, x2 for all results of c2 and x3 for all results of c3. It's a convenient way of doing list comprehension without syntactic sugar. See also mapM and replicateM, which have interesting behaviours in the list monad. Greets Ertugrul -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From edgar.klerks at gmail.com Tue Feb 9 23:49:46 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Tue Feb 9 23:20:55 2010 Subject: [Haskell-beginners] Re: Simplifying code Message-ID: <7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com> Hello all, I have a very interesting alternative solution of the problem. First I generate a tree with all the permutations: eg if I want to find al permutations of ao, I get the following tree [a @] | | [o 0] [o 0] Then I walk trough the tree so I can print it. There is only one ugly thing. Showtree' returns a string (in our example aoa0@o@0). To make it a list i put a \n between a left and right node and then use lines to make it a list of strings. Can someone point me in the right direction how to beautify it a bit? I also have an annoying problem with gmail and firefox. It seems it doesn add my posts to the current thread, but starts a new one. Oh well think I switch to evolution. I will review all yours solutions tomorrow. I saw some very beautifull things. With kind regards, Edgar Klerks module Main where import Data.Char data WordTree = Chain (Char,WordTree) | Choice (Char, WordTree) (Char, WordTree) | Stop instance Show WordTree where show = unlines.showTree type Rule = (Char, Char) type Rules = [Rule] infixl 4 ==> a ==> b = (a,b) rules :: Rules rules = [ 'a' ==> '@', 'l' ==> '|'] buildTree :: String -> Rules -> WordTree buildTree [] r = Stop buildTree (c:cs) r = case lookup c r of Just a -> Choice (a, buildTree cs r) (c, buildTree cs r) Nothing -> Chain (c, buildTree cs r) showTree a = lines $ showTree' a [] showTree' (Chain (a,b)) p = a : showTree' b p showTree' (Choice (a,b) (c,d)) p = c : showTree' d p ++ "\n" ++ (a : showTree' b p) showTree' (Stop) p = p -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100209/175b9dd9/attachment.html From daniel.is.fischer at web.de Wed Feb 10 04:46:03 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 10 04:19:08 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: <201002100031.07292.daniel.is.fischer@web.de> References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002100031.07292.daniel.is.fischer@web.de> Message-ID: <201002101046.03631.daniel.is.fischer@web.de> Am Mittwoch 10 Februar 2010 00:31:07 schrieb Daniel Fischer: > Am Dienstag 09 Februar 2010 23:07:55 schrieb Patrick LeBoutillier: > > Daniel, > > One question though: In the docs sequence is described as: > > > > ? "Evaluate each action in the sequence from left to right, and > > collect the results." > > > > How is one supposed to deduce what the behavior will be for the list > > monad (besides looking at the source)? Or, of course, you could come from the other end. You want to generate the cartesian product of a list of lists. How do you do that? Easy, for each element of the first list, you stick that to the front of each element of the product of the remaining lists: cartesianProduct :: [[a]] -> [[a]] cartesianProduct (l:ls) = [h:t | h <- l, t <- cartesianProduct ls] -- what to do if there is no first list? The cartesian product of an empty set of sets is a one element set, so cartesianProduct [] = [[]] or, cartesianProduct (l:ls) = do h <- l t <- cartesianProduct ls return (h:t) cartesianProduct [] = return [] -- Hey, that's sequence!!! From verdier.jean at gmail.com Wed Feb 10 04:52:24 2010 From: verdier.jean at gmail.com (jean verdier) Date: Wed Feb 10 04:23:35 2010 Subject: [Haskell-beginners] ghc problem Message-ID: <1265795544.2416.10.camel@localhost.localdomain> Trying to compile sources gives me: ghc: internal error: evacuate(static): strange closure type 34 (GHC version 6.10.4 for i386_unknown_linux) Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug This already occured to me some times before and a cleanup and recompile would work. This time i am stuck as i can't compile anymore. The ghc version i use is the 6.10.4 from the ghc home page binary distribution i think. uname -a gives : Linux localhost.localdomain 2.6.29.4-167.fc11.i586 #1 SMP Wed May 27 17:14:37 EDT 2009 i686 athlon i386 GNU/Linux The command line is: ghc -fwarn-incomplete-patterns -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-unused-imports -fno-warn-missing-signatures -fno-glasgow-exts -Werror -outputdir /tmp/mfk/build -package ghc -i/tmp/mfk/gensrc --make common/MFK/Common/SrcGen.hs common/MFK/Common/Conf.hs Any hints ? From daniel.is.fischer at web.de Wed Feb 10 05:27:11 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 10 05:00:13 2010 Subject: [Haskell-beginners] Re: Simplifying code In-Reply-To: <7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com> References: <7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com> Message-ID: <201002101127.12083.daniel.is.fischer@web.de> Am Mittwoch 10 Februar 2010 05:49:46 schrieb edgar klerks: > Hello all, > > I have a very interesting alternative solution of the problem. First I > generate a tree with all the permutations: > > eg if I want to find al permutations of ao, I get the following tree > > [a @] > > [o 0] [o 0] > > Then I walk trough the tree so I can print it. There is only one ugly > thing. Showtree' returns a string (in our example aoa0@o@0). To make it > a list i put a \n between a left and right node and then use lines to > make it a list of strings. Can someone point me in the right direction > how to beautify it a bit? > > I also have an annoying problem with gmail and firefox. It seems it > doesn add my posts to the current thread, but starts a new one. Oh well > think I switch to evolution. Apparently, it doesn't set the in-reply-to field. That should be configurable. > I will review all yours solutions tomorrow. I saw some very beautifull things. > > With kind regards, > > Edgar Klerks > > module Main where > import Data.Char > > data WordTree = Chain (Char,WordTree) Why add the extra tuple? Better: Chain Char WordTree > > | Choice (Char, WordTree) (Char, WordTree) Again, the tuples aren't necessary. > | Stop > > instance Show WordTree where > show = unlines.showTree > > type Rule = (Char, Char) I think it would be better to have type Rule = (Char,[Char]) or even data Rule a = Sub a [a] or use a Map a [a]. You gain more flexibility that way and can use the same code if you can replace a Char (or whatever) with one of any number of possibilities. The WordTree type would then become data WordTree = Branch [(Char, WordTree)] | Tip type Rules = Map Char [Char] rules :: Rules rules = fromList [('a',['a','@']),('l',['l','|'])] subs :: Char -> Rules -> [Char] subs c rs = findWithDefault [c] c rs buildTree :: String -> Rules -> WordTree buildTree (c:cs) rs = let st = buildTree cs rs in Branch [(s,st) | s <- subs c rs] buildTree "" _ = Tip showTree (Branch ts) = [c:xs | (c,st) <- ts, xs <- showTree st] showTree Tip = [""] > type Rules = [Rule] > > infixl 4 ==> > > a ==> b = (a,b) > > rules :: Rules > rules = [ 'a' ==> '@', 'l' ==> '|'] > > > buildTree :: String -> Rules -> WordTree > buildTree [] r = Stop > buildTree (c:cs) r = case lookup c r of > Just a -> Choice (a, buildTree cs r) (c, > buildTree cs r) Share the subtree, Just a -> let st = buildTree cs r in Choice (a,st) (c,st) > Nothing -> Chain (c, buildTree cs r) > > > showTree a = lines $ showTree' a [] > > showTree' (Chain (a,b)) p = a : showTree' b p > showTree' (Choice (a,b) (c,d)) p = c : showTree' d p ++ "\n" ++ (a : > showTree' b p) > showTree' (Stop) p = p showTree :: WordTree -> [String] showTree (Chain (a,b)) = [a:xs | xs <- showTree b] showTree (Choice (a,b) (c,d)) = [a:xs | xs <- showTree b] ++ [c:ys | ys <- showTree d] showTree Stop = [""] From edgar.klerks at gmail.com Wed Feb 10 05:47:09 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Wed Feb 10 05:18:18 2010 Subject: [Haskell-beginners] Re: Simplifying code Message-ID: <7c40819c1002100247v1b287768t54e86df5de809ca6@mail.gmail.com> He Daniel. I have some trouble understanding what you are saying here: >* -- first I need to find the positions of the mutatable charachters. * No, you don't need to do that, it's in general more efficient to not care about positions when dealing with lists. >* findPositions :: [Char] -> [[Int]] *>* findPositions xs = take (length index) $ index <*> [xs] *>* where index = elemIndices <$> leata * [f1, ..., fm] <*> [x1, ..., xn] produces a list of length m*n, so length (index <*> [xs]) == length index * length [xs] == length index ~> remove "take (length index) $" About this piece of code: fmap snd <$> fmap unzip <$> p Prelude Control.Applicative> let p = [[[(1,2),(3,4),(4,5)]]] Prelude Control.Applicative> fmap snd <$> fmap unzip <$> p [[[2,4,5]]] Prelude Control.Applicative> But yeah, it is ridiculously complicated. And I made it up by trial and error and looking at the types. I have a better approach now. I am now building a tree and then walk trough it to collect all the permutations. Thanks for your help and effort! Edgar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/9b5e40f8/attachment.html From asmith9983 at gmail.com Wed Feb 10 06:17:06 2010 From: asmith9983 at gmail.com (Andrew Smith) Date: Wed Feb 10 05:48:17 2010 Subject: [Haskell-beginners] Is there a an include statement equivalence in Haskell Message-ID: <1265800626.9150.27.camel@amd64-ws1> Hi I have a few lines of Haskell which I'd like to be pulled into my Haskell program, similar to the #include in C/C++, or Latex. I don't want to just paste the code permanently using editor, or pass it through say M4, nor build my own module. At the moment its a couple of lines I've used in three or four similar programs. As a Haskell beginner, is my thinking still stuck in the imperative coding style era ? -- Andrew From colin at colina.demon.co.uk Wed Feb 10 06:23:43 2010 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Wed Feb 10 05:54:52 2010 Subject: [Haskell-beginners] Is there a an include statement equivalence in Haskell In-Reply-To: <1265800626.9150.27.camel@amd64-ws1> (Andrew Smith's message of "Wed, 10 Feb 2010 11:17:06 +0000") References: <1265800626.9150.27.camel@amd64-ws1> Message-ID: >>>>> "Andrew" == Andrew Smith writes: Andrew> Hi I have a few lines of Haskell which I'd like to be pulled Andrew> into my Haskell program, similar to the #include in C/C++, Andrew> or Latex. Andrew> I don't want to just paste the code permanently using Andrew> editor, or pass it through say M4, nor build my own module. Andrew> At the moment its a couple of lines I've used in three or Andrew> four similar programs. Andrew> As a Haskell beginner, is my thinking still stuck in the Andrew> imperative coding style era ? The equivalent is import. Modules are lightweight. As are functions. -- Colin Adams Preston Lancashire From gtener at gmail.com Wed Feb 10 06:27:39 2010 From: gtener at gmail.com (=?UTF-8?Q?Krzysztof_Skrz=C4=99tnicki?=) Date: Wed Feb 10 05:58:48 2010 Subject: [Haskell-beginners] Is there a an include statement equivalence in Haskell In-Reply-To: <1265800626.9150.27.camel@amd64-ws1> References: <1265800626.9150.27.camel@amd64-ws1> Message-ID: <220e47b41002100327x5c55fce7of736d0a814e59fe@mail.gmail.com> Hi It's generally bad idea to include source code in this manner. It is error prone, hard to understand and ugly. It's really better to use modules instead. But if you *really* want to rely on such hacks, then yes, it's possible. Simply use cpp's #include. But first you need to enable CPP extension. One way of doing it is writing this line as the first line: > {-# LANGUAGE CPP #-} With cpp in game you can then write: > #include "common.hs" Best regards Krzysztof Skrz?tnicki On Wed, Feb 10, 2010 at 12:17, Andrew Smith wrote: > Hi > I have a few lines of Haskell which I'd like to be pulled into my > Haskell program, similar to the #include in C/C++, or Latex. > > I don't want to just paste the code permanently using editor, ?or pass > it through say M4, nor build my own module. > > At the moment its a couple of lines I've used in three or four similar > programs. > > As a Haskell beginner, is my thinking still stuck in the imperative > coding style era ? > > -- > Andrew > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From stephen.tetley at gmail.com Wed Feb 10 06:28:22 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 10 05:59:32 2010 Subject: [Haskell-beginners] Is there a an include statement equivalence in Haskell In-Reply-To: <1265800626.9150.27.camel@amd64-ws1> References: <1265800626.9150.27.camel@amd64-ws1> Message-ID: <5fdc56d71002100328w4c67979cr4a9d226be21ae43c@mail.gmail.com> Hello Andrew Do the few lines define Haskell expressions (functions or constants) or are they something like a copyright notice (which you want the same in all files)? If they are functions, avoiding putting them in a module would seem a bit dubious. Most people probably have their own collection of 'missing' functions from the Prelude that they share between their projects, (of course everyone has different variations of 'missing' functions...) Best wishes Stephen From edgar.klerks at gmail.com Wed Feb 10 06:31:22 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Wed Feb 10 06:02:48 2010 Subject: [Haskell-beginners] Re: Simplifying code In-Reply-To: 7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com Message-ID: <1265801482.3408.14.camel@edgar-desktop> >Why add the extra tuple? >Better: Chain Char WordTree It feels a bit too loose. Think it is a imperative quirk. I remove the tupples. And I am going to change the type Rule to a Map. I have used that package before and it is fast and easy to use. Another question. I have a book Real World Haskell, which is great, but I would like to read somewhat more indepth stuff. Can you recommend one? Thanks for your advice. With kind regards, Edgar I switched to evolution. Hopefully it will take the in reply to field. From edgar.klerks at gmail.com Wed Feb 10 06:48:07 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Wed Feb 10 06:19:16 2010 Subject: [Haskell-beginners] Simplifying code In-Reply-To: References: <7c40819c1002091211t3df85202od008bea6d1d0a311@mail.gmail.com> <201002092249.18970.daniel.is.fischer@web.de> Message-ID: <7c40819c1002100348g2aa1a512mbb151f2716a6cba5@mail.gmail.com> I found out I get the posts in my mail and I am clicking in the mailinglist. Therefore I am starting new threads over and over again. My apologies. >Why add the extra tuple? >Better: Chain Char WordTree It feels a bit too loose. Think it is a imperative quirk. I remove the tupples. And I am going to change the type Rule to a Map. I have used that package before and it is fast and easy to use. Another question. I have a book Real World Haskell, which is great, but I would like to read somewhat more indepth stuff. Can you recommend one? Thanks for your advice. With kind regards, Edgar I switched to evolution. Hopefully it will take the in reply to field. On Tue, Feb 9, 2010 at 11:07 PM, Patrick LeBoutillier < patrick.leboutillier@gmail.com> wrote: > Daniel, > > > Sure. If you don't mind that the mutations come in a different order, one > > thing that works wonders is "sequence", > > > > sequence :: Monad m => [m a] -> m [a] > > > > In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what > > sequence does, we can write > > > > import Control.Monad (sequence) > > > > generateAll :: String -> [String] > > generateAll word = sequence (map f word) > > where > > f c = case lookup c leat of > > Just r -> [c,r] > > Nothing -> [c] > > That's very nice! > > One question though: In the docs sequence is described as: > > "Evaluate each action in the sequence from left to right, and > collect the results." > > How is one supposed to deduce what the behavior will be for the list > monad (besides looking at the source)? > > > Patrick > > -- > ===================== > Patrick LeBoutillier > Rosem?re, Qu?bec, Canada > -- Flatliner ICT Service, Email: Edgar.klerks@gmail.com, Tel: +31727851429 Fax: +31848363080 Skype: edgar.klerks Website: flatlinerict.nl Adres: Koelmalaan 258, 1813JD, Alkmaar Nederland -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/816852b9/attachment-0001.html From edgar.klerks at gmail.com Wed Feb 10 07:47:58 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Wed Feb 10 07:19:07 2010 Subject: [Haskell-beginners] Re: Simplifying code In-Reply-To: <201002101127.12083.daniel.is.fischer@web.de> References: <7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com> <201002101127.12083.daniel.is.fischer@web.de> Message-ID: <7c40819c1002100447w3f3003berea5fc86a29b0b22e@mail.gmail.com> He Daniel, I use the Data.Map now, this makes it way more flexibler data WordTree > = Branch [(Char, WordTree)] > | Tip > > I only don't use this type of Tree. I am not sure how it works, but it looks good, so I will experiment with it. Is it a so called rose tree? (Then I can find some articles about it). > > Share the subtree, > Just a -> let st = buildTree cs r > in Choice (a,st) (c,st) > > Stupid thing not to do, think I overlooked it :) Thanks again. Edgar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/d96a73d6/attachment.html From edgar.klerks at gmail.com Wed Feb 10 08:31:56 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Wed Feb 10 08:03:06 2010 Subject: [Haskell-beginners] Re: Simplifying code In-Reply-To: <7c40819c1002100447w3f3003berea5fc86a29b0b22e@mail.gmail.com> References: <7c40819c1002092049t36c72b22x2af1dbb4313ba07d@mail.gmail.com> <201002101127.12083.daniel.is.fischer@web.de> <7c40819c1002100447w3f3003berea5fc86a29b0b22e@mail.gmail.com> Message-ID: <7c40819c1002100531y5971254bv60c5ac0979df811e@mail.gmail.com> He Daniel, I used your showTree function because it works better than mine. I also think the program is now truly functional. I will try to implement the other tree on my own to see how it goes. It now looks like this: module Main where import Data.Char import System import qualified Data.Map as M import Control.Applicative ((<$>)) --- CONFIG SECTION --- -- add the characters you want to permutate here-- rules :: Rules rules = M.fromList [ 'a' ==> "@", 'l' ==> "|", 'w' ==> "\\|/", 'v' ==> "\\/", 'o' ==> "0"] data WordTree = Chain String WordTree | Choice String WordTree String WordTree | Stop deriving Show --instance Show WordTree where -- show = unlines.showTree type Rules = M.Map Char [Char] infixl 4 ==> (==>) :: a -> b -> (a, b) a ==> b = (a, b) buildTree :: String -> Rules -> WordTree buildTree [] r = Stop buildTree (c:cs) r = case M.lookup c r of Just a -> let p = buildTree cs r in Choice a p [c] p Nothing -> Chain [c] $ buildTree cs r showTree :: WordTree -> [String] showTree (Chain a b) = [a ++ xs | xs <- showTree b] showTree (Choice a b c d) = [a ++ xs | xs <- showTree b] ++ [c ++ ys | ys <- showTree d] showTree Stop = [""] main :: IO () main = do filename <- head <$> getArgs wordlist <- readFile $ filename let a = (flip buildTree $ rules) <$> (lines wordlist) >>= showTree mapM_ putStrLn a ~ On Wed, Feb 10, 2010 at 1:47 PM, edgar klerks wrote: > He Daniel, > > I use the Data.Map now, this makes it way more flexibler > > > data WordTree >> = Branch [(Char, WordTree)] >> | Tip >> >> > I only don't use this type of Tree. I am not sure how it works, but it > looks good, so I will experiment with it. Is it a so called rose tree? (Then > I can find some articles about it). > > >> >> Share the subtree, >> Just a -> let st = buildTree cs r >> in Choice (a,st) (c,st) >> >> Stupid thing not to do, think I overlooked it :) > > Thanks again. > > Edgar > -- Flatliner ICT Service, Email: Edgar.klerks@gmail.com, Tel: +31727851429 Fax: +31848363080 Skype: edgar.klerks Website: flatlinerict.nl Adres: Koelmalaan 258, 1813JD, Alkmaar Nederland -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/964f8830/attachment.html From bugspynet at gmail.com Wed Feb 10 13:44:11 2010 From: bugspynet at gmail.com (Gabi) Date: Wed Feb 10 13:15:52 2010 Subject: [Haskell-beginners] HackageDB - How to browse by development status Message-ID: <22d241861002101044l1b15352bn731b222d0fc2b343@mail.gmail.com> Hi I really miss the option browsing this big DB by development status (.e.g. alpha,beta,stable,mature,inactive) It is very common (in other langs at least) to have some approx development status. Otherwise it is really hard to choose. How can I know if a package is considered stable enough for production ? -- Regards, Gabi http://bugspy.net From john.moore54 at gmail.com Wed Feb 10 15:16:31 2010 From: john.moore54 at gmail.com (John Moore) Date: Wed Feb 10 14:47:39 2010 Subject: [Haskell-beginners] let expression Message-ID: <4f7ad1ad1002101216n7d51fb96sf5e16a55f03fba42@mail.gmail.com> Hi All, Trying to get this to work, keeps telling me there a parse error on right in the let expression. Can anyone see where the problem is and be able to explain it to me. import Maybe data Expression = Val Double | Add Expression Expression | Subtract Expression Expression | Multiply Expression Expression | Divide Expression Expression | Var String | Let String Expression Expression deriving Show demo1 = (Add(Multiply(Divide(Subtract(Val 25)(Val 5))(Val 10))(Val 7))(Val 30)) type Dict =[(String,Expression)] emptyDict :: Dict emptyDict = [] addEntry :: String->Expression ->Dict -> Dict addEntry n e d = (n,e): d lookupEntry :: String -> Dict -> Maybe Expression lookupEntry n [] = Nothing lookupEntry n (x:xs) = if (n == k) then (Just v) else lookupEntry n xs where (k,v) = x evalStep :: Dict -> Expression -> Expression evalStep d(Val x)= (Val x) evalStep d(Add x y) = case x of (Val a) -> case y of (Val b) -> Val (a+b) left -> Add x (evalStep d y) right -> Add (evalStep d x)y evalStep d(Subtract x y) = case x of (Val a) -> case y of (Val b) -> Val (a-b) left -> Subtract x (evalStep d y) right -> Subtract (evalStep d x)y evalStep d(Multiply x y) = case x of (Val a) -> case y of (Val b) -> Val (a*b) left -> Multiply x (evalStep d y) right -> Multiply (evalStep d x)y evalStep d (Divide x y) = case x of (Val a) -> case y of (Val b) -> Val (a/b) left -> Divide x (evalStep d y) right -> Divide (evalStep d x)y evalStep d (Let n e1 e2) = case e1 of (Val a) -> case e2 of (Val b)-> Val (Let e1 e2) left -> Let e1 (evalStep d e2) right -> Let (evalStep d e1) e2 evaluate :: Dict-> [Expression] -> Expression -> IO() evaluate d(x:xs) e = do putStrLn (show e) putStrLn "Do another step (y/n) or rollback (r)? :" c <- getLine case c of "y" -> let e'= (evalStep d e)in evaluate d (e:x:xs) e'-- build up history "r" -> case (x:xs) of (x:xs)-> evaluate d xs x []-> do { putStrLn "Empty" ;evaluate d(x:xs) e } "n" -> putStrLn $ "Ok you said no :" ++ c John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/512a91cc/attachment.html From stephen.tetley at gmail.com Wed Feb 10 15:26:34 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 10 14:57:43 2010 Subject: [Haskell-beginners] let expression In-Reply-To: <4f7ad1ad1002101216n7d51fb96sf5e16a55f03fba42@mail.gmail.com> References: <4f7ad1ad1002101216n7d51fb96sf5e16a55f03fba42@mail.gmail.com> Message-ID: <5fdc56d71002101226xc5c90fdobf1fb1d74dfdea5b@mail.gmail.com> Hi John Provided the whitespace doesn't get mangled in the mail the last evalStep needs indenting correctly: evalStep d (Let n e1 e2) = case e1 of (Val a) -> case e2 of (Val b)-> Val (Let e1 e2) left -> Let e1 (evalStep d e2) right -> Let (evalStep d e1) e2 Also the "r" case in evaluate: "r" -> case (x:xs) of (x:xs) -> evaluate d xs x [] -> do { putStrLn "Empty" ;evaluate d(x:xs) e } You might want to consider using wildcards (i.e. underscores) _ rather than variables e.g 'left' and 'right' when you don't use the value of a pattern match at the right of the "->". Best wishes Stephen On 10 February 2010 20:16, John Moore wrote: > Hi All, > ???????? Trying to get this to work, keeps telling me there a parse error on > right in the let expression. Can anyone see where the problem is and be able > to explain it to me. > > import Maybe > data Expression = Val Double > ?????????????? | Add Expression Expression > ?????????????? | Subtract Expression Expression > ?????????????? | Multiply Expression Expression > ?????????????? | Divide Expression Expression > ??????? | Var String > ??????? | Let String Expression Expression > ??????? deriving Show > demo1 = (Add(Multiply(Divide(Subtract(Val 25)(Val 5))(Val 10))(Val 7))(Val > 30)) > type Dict =[(String,Expression)] > emptyDict :: Dict > emptyDict = [] > addEntry :: String->Expression ->Dict -> Dict > addEntry n e d = (n,e): d > lookupEntry :: String -> Dict -> Maybe Expression > lookupEntry n [] = Nothing > lookupEntry n (x:xs) = if (n == k) > ???then (Just v) > ??????????????? else lookupEntry n xs > ???where (k,v) = x > evalStep :: Dict -> Expression ->? Expression > evalStep d(Val x)=?? (Val x) > evalStep d(Add x y) > ? = case x of > ????? (Val a) -> case y of > ?????????????????? (Val b) ->? Val (a+b) > ?????????????????? left -> Add x (evalStep d y) > ????? right -> Add (evalStep d x)y > evalStep d(Subtract x y) > ? = case x of > ????? (Val a) -> case y of > ?????????????????? (Val b) -> Val (a-b) > ?????????????????? left -> Subtract x (evalStep d y) > ????? right -> Subtract (evalStep d x)y > evalStep d(Multiply x y) > ? = case x of > ????? (Val a) -> case y of > ?????????????????? (Val b) -> Val (a*b) > ?????????????????? left -> Multiply x (evalStep d y) > ????? right -> Multiply (evalStep d x)y > evalStep d (Divide x y) > ? = case x of > ????? (Val a) -> case y of > ?????????????????? (Val b) -> Val (a/b) > ?????????????????? left -> Divide x (evalStep d y) > ????? right -> Divide (evalStep d x)y > evalStep d (Let n e1 e2) > ?? = case e1 of > ?????? (Val a) -> case e2 of > ??(Val b)-> Val (Let e1 e2) > ?????? ??left -> Let e1 (evalStep d e2) > ????? right -> Let (evalStep d e1) e2 > > > evaluate :: Dict-> [Expression] -> Expression -> IO() > evaluate d(x:xs) e = do > ???? putStrLn (show e) > ???? putStrLn "Do another step (y/n) or rollback (r)? :" > ???? c <- getLine > ???? case c of > ?????? "y" -> let e'= (evalStep d e)in evaluate d (e:x:xs) e'-- build up > history > > ?????? "r" ->? case (x:xs) of > ??(x:xs)-> evaluate d xs x > ??[]-> do { putStrLn "Empty" > ???;evaluate d(x:xs) e > ??} > ?????? "n"? ->? putStrLn $ "Ok you said no :" ++ c > > > John > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > From daniel.is.fischer at web.de Wed Feb 10 15:32:16 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 10 15:05:17 2010 Subject: [Haskell-beginners] let expression In-Reply-To: <4f7ad1ad1002101216n7d51fb96sf5e16a55f03fba42@mail.gmail.com> References: <4f7ad1ad1002101216n7d51fb96sf5e16a55f03fba42@mail.gmail.com> Message-ID: <201002102132.16439.daniel.is.fischer@web.de> Am Mittwoch 10 Februar 2010 21:16:31 schrieb John Moore: > Hi All, > Trying to get this to work, keeps telling me there a parse > error on right in the let expression. Can anyone see where the problem > is and be able to explain it to me. > > evalStep d (Let n e1 e2) > = case e1 of > (Val a) -> case e2 of > (Val b)-> Val (Let e1 e2) > left -> Let e1 (evalStep d e2) > right -> Let (evalStep d e1) e2 Here? Indentation. The patterns for the inner case-expression must be indented further than those for the outer (and all patterns in one case-expression must be indented to the same level). > > > evaluate :: Dict-> [Expression] -> Expression -> IO() > evaluate d(x:xs) e = do > putStrLn (show e) > putStrLn "Do another step (y/n) or rollback (r)? :" > c <- getLine > case c of > "y" -> let e'= (evalStep d e)in evaluate d (e:x:xs) e'-- build up > history > > "r" -> case (x:xs) of > (x:xs)-> evaluate d xs x > []-> do { putStrLn "Empty" > ;evaluate d(x:xs) e > } > "n" -> putStrLn $ "Ok you said no :" ++ c > > > John From stephen.tetley at gmail.com Wed Feb 10 15:39:44 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 10 15:10:56 2010 Subject: [Haskell-beginners] HackageDB - How to browse by development status In-Reply-To: <22d241861002101044l1b15352bn731b222d0fc2b343@mail.gmail.com> References: <22d241861002101044l1b15352bn731b222d0fc2b343@mail.gmail.com> Message-ID: <5fdc56d71002101239n37421e9co707e121f63001f7c@mail.gmail.com> Hi Gabi Unfortunately 'stability' is only an optional field in cabal files, so some projects will display it but others don't. Roel van Dijk has a nice project that allows you to see reverse dependencies for packages in HackageDB and this gives you a popularity rank. As a rule of thumb, a package won't be very popular if it is unstable... http://www.haskell.org/pipermail/haskell-cafe/2009-October/067765.html http://bifunctor.homelinux.net/~roel/hackage/packages/hackage.html http://bifunctor.homelinux.net/~roel/hackage/packages/archive/revdeps-list.html You can judge inactivity by last release, but some great packages 'just work' so don't need updating. Best wishes Stephen From kane96 at gmx.de Wed Feb 10 15:52:48 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Wed Feb 10 15:24:03 2010 Subject: [Haskell-beginners] consing an element to a list inside a file Message-ID: <20100210205248.215170@gmx.net> Hi, I want to add an element to a list inside a haskell file: mylist = [1,2,3,4] 0:mylist in Prelude it works fine, but when I do it in a file I get the error: parse error (possibly incorrect indentation) Failed, modules loaded: none. in a line after this two that doesn't exist -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From byorgey at seas.upenn.edu Wed Feb 10 15:54:32 2010 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Feb 10 15:25:39 2010 Subject: [Haskell-beginners] ghc problem In-Reply-To: <1265795544.2416.10.camel@localhost.localdomain> References: <1265795544.2416.10.camel@localhost.localdomain> Message-ID: <20100210205432.GA2944@seas.upenn.edu> This is clearly a GHC bug of some sort. Have you tried looking for this error on the GHC bug tracker? It's possible it's already been fixed in a newer version of GHC.Otherwise, I suggest emailing the GHC user mailing list. -Brent On Wed, Feb 10, 2010 at 10:52:24AM +0100, jean verdier wrote: > Trying to compile sources gives me: > > ghc: internal error: evacuate(static): strange closure type 34 > (GHC version 6.10.4 for i386_unknown_linux) > Please report this as a GHC bug: > http://www.haskell.org/ghc/reportabug > > This already occured to me some times before and a cleanup and recompile > would work. This time i am stuck as i can't compile anymore. The ghc > version i use is the 6.10.4 from the ghc home page binary distribution i > think. > > uname -a gives : > Linux localhost.localdomain 2.6.29.4-167.fc11.i586 #1 SMP Wed May 27 > 17:14:37 EDT 2009 i686 athlon i386 GNU/Linux > > The command line is: > ghc -fwarn-incomplete-patterns -fno-warn-unused-binds > -fno-warn-unused-matches -fno-warn-unused-imports > -fno-warn-missing-signatures -fno-glasgow-exts -Werror > -outputdir /tmp/mfk/build -package ghc -i/tmp/mfk/gensrc --make > common/MFK/Common/SrcGen.hs common/MFK/Common/Conf.hs > > Any hints ? > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From byorgey at seas.upenn.edu Wed Feb 10 16:00:35 2010 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Feb 10 15:31:44 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100210205248.215170@gmx.net> References: <20100210205248.215170@gmx.net> Message-ID: <20100210210034.GB2944@seas.upenn.edu> On Wed, Feb 10, 2010 at 09:52:48PM +0100, kane96@gmx.de wrote: > Hi, > I want to add an element to a list inside a haskell file: > mylist = [1,2,3,4] > 0:mylist > in Prelude it works fine, but when I do it in a file I get the error: > parse error (possibly incorrect indentation) > Failed, modules loaded: none. > in a line after this two that doesn't exist A Haskell file is simply a list of declarations, i.e. definitions of data types, classes, and functions. You cannot just have an expression by itself in a Haskell file. You can write expressions at a ghci prompt (which I assume is what you meant) because that is what ghci is for: evaluating expressions. Why do you want 0:mylist by itself in a Haskell file? What is its purpose? Note that it will not modify the value of mylist (indeed, you *cannot* modify the value of mylist once it has been defined). -Brent From kane96 at gmx.de Wed Feb 10 16:06:23 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Wed Feb 10 15:37:39 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100210210034.GB2944@seas.upenn.edu> References: <20100210205248.215170@gmx.net> <20100210210034.GB2944@seas.upenn.edu> Message-ID: <20100210210623.264870@gmx.net> It's just a part of a more complex exercise I have to read an input of the user. After that he can decide if he wants to add another input. If not, all inputs the user did should be printed on the screen. So I want to add each input to a list and print the list at the end. -------- Original-Nachricht -------- > Datum: Wed, 10 Feb 2010 16:00:35 -0500 > Von: Brent Yorgey > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > On Wed, Feb 10, 2010 at 09:52:48PM +0100, kane96@gmx.de wrote: > > Hi, > > I want to add an element to a list inside a haskell file: > > mylist = [1,2,3,4] > > 0:mylist > > in Prelude it works fine, but when I do it in a file I get the error: > > parse error (possibly incorrect indentation) > > Failed, modules loaded: none. > > in a line after this two that doesn't exist > > A Haskell file is simply a list of declarations, i.e. definitions of > data types, classes, and functions. You cannot just have an > expression by itself in a Haskell file. You can write expressions at > a ghci prompt (which I assume is what you meant) because that is what > ghci is for: evaluating expressions. > > Why do you want 0:mylist by itself in a Haskell file? What is its > purpose? Note that it will not modify the value of mylist (indeed, > you *cannot* modify the value of mylist once it has been defined). > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From kane96 at gmx.de Wed Feb 10 16:06:23 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Wed Feb 10 15:37:43 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100210210034.GB2944@seas.upenn.edu> References: <20100210205248.215170@gmx.net> <20100210210034.GB2944@seas.upenn.edu> Message-ID: <20100210210623.264870@gmx.net> It's just a part of a more complex exercise I have to read an input of the user. After that he can decide if he wants to add another input. If not, all inputs the user did should be printed on the screen. So I want to add each input to a list and print the list at the end. -------- Original-Nachricht -------- > Datum: Wed, 10 Feb 2010 16:00:35 -0500 > Von: Brent Yorgey > An: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > On Wed, Feb 10, 2010 at 09:52:48PM +0100, kane96@gmx.de wrote: > > Hi, > > I want to add an element to a list inside a haskell file: > > mylist = [1,2,3,4] > > 0:mylist > > in Prelude it works fine, but when I do it in a file I get the error: > > parse error (possibly incorrect indentation) > > Failed, modules loaded: none. > > in a line after this two that doesn't exist > > A Haskell file is simply a list of declarations, i.e. definitions of > data types, classes, and functions. You cannot just have an > expression by itself in a Haskell file. You can write expressions at > a ghci prompt (which I assume is what you meant) because that is what > ghci is for: evaluating expressions. > > Why do you want 0:mylist by itself in a Haskell file? What is its > purpose? Note that it will not modify the value of mylist (indeed, > you *cannot* modify the value of mylist once it has been defined). > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Wed Feb 10 16:21:13 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 10 15:54:15 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100210205248.215170@gmx.net> References: <20100210205248.215170@gmx.net> Message-ID: <201002102221.13418.daniel.is.fischer@web.de> Am Mittwoch 10 Februar 2010 21:52:48 schrieb kane96@gmx.de: > Hi, > I want to add an element to a list inside a haskell file: > mylist = [1,2,3,4] > 0:mylist > in Prelude it works fine, but when I do it in a file I get the error: > parse error (possibly incorrect indentation) > Failed, modules loaded: none. > in a line after this two that doesn't exist 0:mylist is a plain value. At the ghci or hugs prompt, if you enter an expression (4, 3*7+5, [0 .. 10],...), that means "evaluate the expression and print the result" (unless it's a value of type IO a, then it means "execute this action"). In a source file, you write definitions, name = expression to be bound to name func arg1 arg2 = body etc. You can have pattern bindings in a source file, (a,b) = ([0 .. 100],True) -- defines a and b 0:mylist = map (`mod` 7) [14 .. 100] -- defines mylist as [1,2,3,4,5,6,0,1,...,1,2] 0:myotherlist = [4,5,6] {- will fail with ghci> myotherlist *** Exception: PatTest.hs:4:0-22: Irrefutable pattern failed for pattern 0 : myotherlist when demanded -} , so that's what the parser expected, a '=' and an expression which defines mylist. Since it didn't find a '=' on the same line, it tried the next (where it found end of file, another definition or whatever) where it reported the parse error. Probably you wanted mysecondlist = 0:mylist ? From bugspynet at gmail.com Thu Feb 11 01:58:54 2010 From: bugspynet at gmail.com (Gabi) Date: Thu Feb 11 01:29:59 2010 Subject: [Haskell-beginners] HackageDB - How to browse by development status Message-ID: <22d241861002102258k68e449eah51653ba26b3a1518@mail.gmail.com> Thanks Stephen This is really useful link. At least now I can guess what package is "popular" what is esoteric. -- Regards, Gabi http://bugspy.net From verdier.jean at gmail.com Thu Feb 11 02:56:19 2010 From: verdier.jean at gmail.com (jean verdier) Date: Thu Feb 11 02:27:27 2010 Subject: [Haskell-beginners] ghc problem In-Reply-To: <20100210205432.GA2944@seas.upenn.edu> References: <1265795544.2416.10.camel@localhost.localdomain> <20100210205432.GA2944@seas.upenn.edu> Message-ID: <1265874979.2413.12.camel@localhost.localdomain> Thx for your reply. I've switched back to the yum version (6.10.3) and it works. The problem was too mysterious with the 6.10.4 i had and it does not seem common so i might have done something stupid at some point with my install. Tried to find a bug and got Oops? Trac detected an internal error: OperationalError: database is locked So i guess i'll stick with the yumed 6.10.3 :) On Wed, 2010-02-10 at 15:54 -0500, Brent Yorgey wrote: > This is clearly a GHC bug of some sort. Have you tried looking for > this error on the GHC bug tracker? It's possible it's already been > fixed in a newer version of GHC.Otherwise, I suggest emailing the GHC > user mailing list. > > -Brent > > > On Wed, Feb 10, 2010 at 10:52:24AM +0100, jean verdier wrote: > > Trying to compile sources gives me: > > > > ghc: internal error: evacuate(static): strange closure type 34 > > (GHC version 6.10.4 for i386_unknown_linux) > > Please report this as a GHC bug: > > http://www.haskell.org/ghc/reportabug > > > > This already occured to me some times before and a cleanup and recompile > > would work. This time i am stuck as i can't compile anymore. The ghc > > version i use is the 6.10.4 from the ghc home page binary distribution i > > think. > > > > uname -a gives : > > Linux localhost.localdomain 2.6.29.4-167.fc11.i586 #1 SMP Wed May 27 > > 17:14:37 EDT 2009 i686 athlon i386 GNU/Linux > > > > The command line is: > > ghc -fwarn-incomplete-patterns -fno-warn-unused-binds > > -fno-warn-unused-matches -fno-warn-unused-imports > > -fno-warn-missing-signatures -fno-glasgow-exts -Werror > > -outputdir /tmp/mfk/build -package ghc -i/tmp/mfk/gensrc --make > > common/MFK/Common/SrcGen.hs common/MFK/Common/Conf.hs > > > > Any hints ? > > > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From kane96 at gmx.de Thu Feb 11 15:09:37 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 11 14:40:46 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002102221.13418.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002102221.13418.daniel.is.fischer@web.de> Message-ID: <20100211200937.193060@gmx.net> mysecondlist = 0:mylist that's was I was searching for, but how can I add the element to the same list? I have to get any number of inputs from the user and at the end, if he doesn't want to make more inputs, I have to print a list with all the inputs he did. -------- Original-Nachricht -------- > Datum: Wed, 10 Feb 2010 22:21:13 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Mittwoch 10 Februar 2010 21:52:48 schrieb kane96@gmx.de: > > Hi, > > I want to add an element to a list inside a haskell file: > > mylist = [1,2,3,4] > > 0:mylist > > in Prelude it works fine, but when I do it in a file I get the error: > > parse error (possibly incorrect indentation) > > Failed, modules loaded: none. > > in a line after this two that doesn't exist > > 0:mylist > > is a plain value. At the ghci or hugs prompt, if you enter an expression > (4, 3*7+5, [0 .. 10],...), that means "evaluate the expression and print > the result" (unless it's a value of type IO a, then it means "execute this > action"). > In a source file, you write definitions, > > name = expression to be bound to name > > func arg1 arg2 = body > > etc. > > You can have pattern bindings in a source file, > > (a,b) = ([0 .. 100],True) > > -- defines a and b > > 0:mylist = map (`mod` 7) [14 .. 100] > > -- defines mylist as [1,2,3,4,5,6,0,1,...,1,2] > > 0:myotherlist = [4,5,6] > > {- will fail with > ghci> myotherlist > *** Exception: PatTest.hs:4:0-22: Irrefutable pattern failed for pattern 0 > : myotherlist > > when demanded > -} > , so that's what the parser expected, a '=' and an expression which > defines > mylist. > Since it didn't find a '=' on the same line, it tried the next (where it > found end of file, another definition or whatever) where it reported the > parse error. > > Probably you wanted > > mysecondlist = 0:mylist > > ? -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From daniel.is.fischer at web.de Thu Feb 11 15:41:15 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 11 15:14:15 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100211200937.193060@gmx.net> References: <20100210205248.215170@gmx.net> <201002102221.13418.daniel.is.fischer@web.de> <20100211200937.193060@gmx.net> Message-ID: <201002112141.15455.daniel.is.fischer@web.de> Am Donnerstag 11 Februar 2010 21:09:37 schrieb kane96@gmx.de: > mysecondlist = 0:mylist > > that's was I was searching for, but how can I add the element to the > same list? You can't. When you add an element to a list, it's a different list. > I have to get any number of inputs from the user and at the > end, if he doesn't want to make more inputs, I have to print a list with > all the inputs he did. Make the list a parameter of the input loop. getInputs previous = do user <- getUserInput if endNow user then printList previous else getInputs (user:previous) From kane96 at gmx.de Thu Feb 11 16:34:45 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 11 16:05:52 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002112141.15455.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002102221.13418.daniel.is.fischer@web.de> <20100211200937.193060@gmx.net> <201002112141.15455.daniel.is.fischer@web.de> Message-ID: <20100211213445.193020@gmx.net> the problem is the function should be readMyDatatype :: IO MyDatatype readMyDatatype = do ... Is it possible to do it somehow different without a parameter? -------- Original-Nachricht -------- > Datum: Thu, 11 Feb 2010 21:41:15 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Donnerstag 11 Februar 2010 21:09:37 schrieb kane96@gmx.de: > > mysecondlist = 0:mylist > > > > that's was I was searching for, but how can I add the element to the > > same list? > > You can't. When you add an element to a list, it's a different list. > > > I have to get any number of inputs from the user and at the > > end, if he doesn't want to make more inputs, I have to print a list with > > all the inputs he did. > > Make the list a parameter of the input loop. > > getInputs previous = do > user <- getUserInput > if endNow user > then printList previous > else getInputs (user:previous) -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From daniel.is.fischer at web.de Thu Feb 11 16:54:59 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 11 16:27:59 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100211213445.193020@gmx.net> References: <20100210205248.215170@gmx.net> <201002112141.15455.daniel.is.fischer@web.de> <20100211213445.193020@gmx.net> Message-ID: <201002112255.00064.daniel.is.fischer@web.de> Am Donnerstag 11 Februar 2010 22:34:45 schrieb kane96@gmx.de: > the problem is the function should be > readMyDatatype :: IO MyDatatype > readMyDatatype = do ... > Is it possible to do it somehow different without a parameter? Separate the worker from the API function. API: readMyDatatype :: IO MyDatatype readMyDatatype = call worker with appropriate arguments worker: readMD :: t1 -> t2 -> ... -> tn -> IO MyDatatype > > -------- Original-Nachricht -------- > > > Datum: Thu, 11 Feb 2010 21:41:15 +0100 > > Von: Daniel Fischer > > An: kane96@gmx.de > > CC: beginners@haskell.org > > Betreff: Re: [Haskell-beginners] consing an element to a list inside a > > file > > > > Am Donnerstag 11 Februar 2010 21:09:37 schrieb kane96@gmx.de: > > > mysecondlist = 0:mylist > > > > > > that's was I was searching for, but how can I add the element to the > > > same list? > > > > You can't. When you add an element to a list, it's a different list. > > > > > I have to get any number of inputs from the user and at the > > > end, if he doesn't want to make more inputs, I have to print a list > > > with all the inputs he did. > > > > Make the list a parameter of the input loop. > > > > getInputs previous = do > > user <- getUserInput > > if endNow user > > then printList previous > > else getInputs (user:previous) From kane96 at gmx.de Thu Feb 11 17:04:01 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 11 16:35:09 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002112255.00064.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002112141.15455.daniel.is.fischer@web.de> <20100211213445.193020@gmx.net> <201002112255.00064.daniel.is.fischer@web.de> Message-ID: <20100211220401.193040@gmx.net> but the exercise was nearly complete on the sheet and I just have to complete two parts and one of them is to ask the user if he want's to do more input. If so, I have to let him input a new value (triple) for MyDatatype, otherwise I have to print the list with all triples -------- Original-Nachricht -------- > Datum: Thu, 11 Feb 2010 22:54:59 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Donnerstag 11 Februar 2010 22:34:45 schrieb kane96@gmx.de: > > the problem is the function should be > > readMyDatatype :: IO MyDatatype > > readMyDatatype = do ... > > Is it possible to do it somehow different without a parameter? > > Separate the worker from the API function. > > API: > > readMyDatatype :: IO MyDatatype > readMyDatatype = call worker with appropriate arguments > > worker: > > readMD :: t1 -> t2 -> ... -> tn -> IO MyDatatype > > > > > -------- Original-Nachricht -------- > > > > > Datum: Thu, 11 Feb 2010 21:41:15 +0100 > > > Von: Daniel Fischer > > > An: kane96@gmx.de > > > CC: beginners@haskell.org > > > Betreff: Re: [Haskell-beginners] consing an element to a list inside a > > > file > > > > > > Am Donnerstag 11 Februar 2010 21:09:37 schrieb kane96@gmx.de: > > > > mysecondlist = 0:mylist > > > > > > > > that's was I was searching for, but how can I add the element to the > > > > same list? > > > > > > You can't. When you add an element to a list, it's a different list. > > > > > > > I have to get any number of inputs from the user and at the > > > > end, if he doesn't want to make more inputs, I have to print a list > > > > with all the inputs he did. > > > > > > Make the list a parameter of the input loop. > > > > > > getInputs previous = do > > > user <- getUserInput > > > if endNow user > > > then printList previous > > > else getInputs (user:previous) -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From daniel.is.fischer at web.de Thu Feb 11 17:30:05 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 11 17:03:20 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100211220401.193040@gmx.net> References: <20100210205248.215170@gmx.net> <201002112255.00064.daniel.is.fischer@web.de> <20100211220401.193040@gmx.net> Message-ID: <201002112330.05615.daniel.is.fischer@web.de> Am Donnerstag 11 Februar 2010 23:04:01 schrieb kane96@gmx.de: > but the exercise was nearly complete on the sheet and I just have to > complete two parts and one of them is to ask the user if he want's to do > more input. If so, I have to let him input a new value (triple) for > MyDatatype, otherwise I have to print the list with all triples > But to print it, you need to have a reference to the list of inputs. The easiest way is to have it as a parameter in the worker loop. What *exactly* is your task? What is given and what are the specifications for a solution? > > > > Am Donnerstag 11 Februar 2010 22:34:45 schrieb kane96@gmx.de: > > > the problem is the function should be > > > readMyDatatype :: IO MyDatatype > > > readMyDatatype = do ... > > > Is it possible to do it somehow different without a parameter? > > > > Separate the worker from the API function. > > > > API: > > > > readMyDatatype :: IO MyDatatype > > readMyDatatype = call worker with appropriate arguments > > > > worker: > > > > readMD :: t1 -> t2 -> ... -> tn -> IO MyDatatype From bugspynet at gmail.com Fri Feb 12 04:31:49 2010 From: bugspynet at gmail.com (Gabi) Date: Fri Feb 12 04:02:52 2010 Subject: [Haskell-beginners] Data.Tree computation Message-ID: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> Hi guys, I've tried to use Data.Tree as a computation tree (each node is numerical function, each leaf is a terminal) It kinda works, but the code seems very verbose. How can it made more concise ? I am sure I missed a lot of shortcuts and idioms. -- file t.hs import qualified Data.Tree as T data Term = TInt Int| TDouble Double deriving (Show, Eq) data Func = Plus | Minus | Mult | Div deriving (Show, Eq) data ANode = GFunc Func | GTerm Term deriving (Show, Eq) fNode :: Func -> T.Forest ANode-> T.Tree ANode fNode f = T.Node (GFunc f) tNode:: Term -> T.Tree ANode tNode t = T.Node (GTerm t) [] calc :: T.Tree ANode -> Double calc (T.Node (GTerm (TInt n))[]) = fromIntegral n :: Double calc (T.Node (GFunc Plus) xs ) = foldl1 (+) (map calc xs) calc (T.Node (GFunc Minus) xs ) = foldl1 (-) (map calc xs) calc (T.Node (GFunc Mult) xs ) = foldl1 (*) (map calc xs) calc (T.Node (GFunc Div) xs ) = foldl1 (/) (map calc xs) -- (/ (+ 5 5 (- 10 100)) 10) - calc Should return -8.0 aTree = fNode Div [fNode Plus [tNode $ TInt 5,tNode $ TInt 5, fNode Minus [tNode $ TInt 10,tNode $ TInt 100]], tNode (TInt 10)] Regards, Gabi http://bugspy.net From apfelmus at quantentunnel.de Fri Feb 12 05:48:00 2010 From: apfelmus at quantentunnel.de (Heinrich Apfelmus) Date: Fri Feb 12 05:19:26 2010 Subject: [Haskell-beginners] Re: Data.Tree computation In-Reply-To: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> References: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> Message-ID: Gabi wrote: > I've tried to use Data.Tree as a computation tree (each node is > numerical function, each leaf is a terminal) > It kinda works, but the code seems very verbose. How can it made more > concise ? I am sure I missed a lot of shortcuts and idioms. > > -- file t.hs > import qualified Data.Tree as T > > data Term = TInt Int| TDouble Double > deriving (Show, Eq) > > data Func = Plus | Minus | Mult | Div > deriving (Show, Eq) > > data ANode = GFunc Func | GTerm Term > deriving (Show, Eq) > > fNode :: Func -> T.Forest ANode-> T.Tree ANode > fNode f = T.Node (GFunc f) > > tNode:: Term -> T.Tree ANode > tNode t = T.Node (GTerm t) [] > > calc :: T.Tree ANode -> Double > calc (T.Node (GTerm (TInt n))[]) = fromIntegral n :: Double > calc (T.Node (GFunc Plus) xs ) = foldl1 (+) (map calc xs) > calc (T.Node (GFunc Minus) xs ) = foldl1 (-) (map calc xs) > calc (T.Node (GFunc Mult) xs ) = foldl1 (*) (map calc xs) > calc (T.Node (GFunc Div) xs ) = foldl1 (/) (map calc xs) How about calc :: T.Tree ANode -> Double calc (T.Node (GTerm sym) []) = term sym where term (TInt n) = fromIntegral n term (TDouble d) = d calc (T.Node (GFunc sym) xs) = foldl1 (op sym) (map calc xs) where op Plus = (+) op Minus = (-) op Mult = (*) op Div = (/) By the way, Data.Tree is not used very often, people usually roll their own syntax trees because it's so easy. data Expr = V Value | App Fun [Expr] data Value = VInt Int | VDouble Double data Fun = Plus | Minus | Mult | Div eval :: Expr -> Double eval (V (VInt n)) = fromIntegral n eval (V (VDouble d)) = d eval (App sym xs ) = foldl1 (op sym) (map eval xs) where op Plus = ... Regards, Heinrich Apfelmus -- http://apfelmus.nfshost.com From stephen.tetley at gmail.com Fri Feb 12 05:48:57 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Feb 12 05:20:03 2010 Subject: [Haskell-beginners] Data.Tree computation In-Reply-To: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> References: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> Message-ID: <5fdc56d71002120248n701c0da2n896c576de92040@mail.gmail.com> Hello One idiom is to avoid Data.Tree unless you really have a "rose tree" - Haskell's algebraic data types model trees. Note this one is a binary tree rather than a "rose tree" - _plus_ doesn't work quite the same as it did in your original. (+ 1 2 3 4) == (+ 1 (+ 2 (+ 3 4))) data Val = VInt Int | VDbl Double deriving (Eq,Ord,Show) data Op = Plus | Minus | Mult | Div deriving (Eq,Ord,Show) -- Note this is a binary tree -- Data.Tree is a "rose tree" data Tree = Tree { operator :: Op , left_branch :: Tree , right_branch :: Tree } | Leaf { value :: Val } deriving (Eq,Show) -- Or whithout field labels: -- data Tree = Tree Op Tree Tree -- | Leaf Val calc :: Tree -> Double calc (Leaf v) = val v calc (Tree Plus l r) = calc l + calc r calc (Tree Minus l r) = calc l - calc r calc (Tree Mult l r) = calc l * calc r calc (Tree Div l r) = calc l / calc r val :: Val -> Double val (VInt i) = fromIntegral i val (VDbl d) = d -- "wrapped" constructors dblLeaf :: Double -> Tree dblLeaf d = Leaf $ VDbl d intLeaf :: Int -> Tree intLeaf i = Leaf $ VInt i -- simulates: (+ a b c ... n) -- plus :: [Tree] -> Tree plus [] = error "Bad plus" plus [a] = a plus (a:as) = Tree Plus a (plus as) -- (/ (+ 5 5 (- 10 100)) 10) - calc Should return -8.0 aTree :: Tree aTree = Tree Div (plus [ intLeaf 5 , intLeaf 5 , Tree Minus (intLeaf 10) (intLeaf 100) ]) (intLeaf 10) demo1 = calc aTree ----------------------------------------------------------------- Once you've made the tree type concrete there are other variations you can consider. E.g, a polymorphic tree - leaf type is a parameter: data Tree a = Tree Op (Tree a) (Tree a) | Leaf a deriving (Eq,Show) Or you could really wanted a multiple argument plus: data Op2 = Minus' | Mult' | Div' deriving (Eq,Ord,Show) data Tree2 = Tree Op2 Tree Tree | MultiPlus [Tree] | Leaf Val ... although once things start going irregular, they often cause problems later. Best wishes Stephen From bugspynet at gmail.com Fri Feb 12 09:30:48 2010 From: bugspynet at gmail.com (Gabi) Date: Fri Feb 12 09:01:50 2010 Subject: [Haskell-beginners] Re: Data.Tree computation In-Reply-To: <5fdc56d71002120248n701c0da2n896c576de92040@mail.gmail.com> References: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> <5fdc56d71002120248n701c0da2n896c576de92040@mail.gmail.com> Message-ID: <22d241861002120630y3ebe1cd9jb4fad908331ff342@mail.gmail.com> The reason I wanted to use Data.Tree instead of my own is that I hoped to serliaze it using Data.Binary (which supposed to support Data.Tree) Alas, It doesn't work. Need to figure it out yet.. *Main Data.Binary Data.Tree> :m +Data.Binary *Main Data.Binary Data.Tree> encode aTree :1:0: No instance for (Binary ANode) arising from a use of `encode' at :1:0-11 Possible fix: add an instance declaration for (Binary ANode) In the expression: encode aTree In the definition of `it': it = encode aTree -- Regards, Gabi http://bugspy.net From stephen.tetley at gmail.com Fri Feb 12 10:24:53 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Feb 12 09:55:55 2010 Subject: [Haskell-beginners] Re: Data.Tree computation In-Reply-To: <22d241861002120630y3ebe1cd9jb4fad908331ff342@mail.gmail.com> References: <22d241861002120131u49feb88br853218c8825349bb@mail.gmail.com> <5fdc56d71002120248n701c0da2n896c576de92040@mail.gmail.com> <22d241861002120630y3ebe1cd9jb4fad908331ff342@mail.gmail.com> Message-ID: <5fdc56d71002120724r7c633c23l73f728cfa9207c69@mail.gmail.com> Hello Gabi The docs for Data.Binary use a binary tree as an example - see about half way down the page... http://hackage.haskell.org/packages/archive/binary/0.5.0.2/doc/html/Data-Binary.html On 12 February 2010 14:30, Gabi wrote: > The reason I wanted to use Data.Tree instead of my own is that I hoped > to serliaze it using Data.Binary (which supposed to support Data.Tree) > Alas, It doesn't work. Need to figure it out yet.. > From kane96 at gmx.de Fri Feb 12 14:15:26 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Feb 12 13:46:31 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002112330.05615.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002112255.00064.daniel.is.fischer@web.de> <20100211220401.193040@gmx.net> <201002112330.05615.daniel.is.fischer@web.de> Message-ID: <20100212191526.81280@gmx.net> the exercise looks like that: readMyCal :: IO MyCalendar readMyCal = do putStr "day: " d <- readInt putStr "month: " m <- readMonth putStr "year: " y <- readInt let mydate = (d,m,y) if not (legalDate mydate) then do putStrLn "wrong" --COMPLETE-1-- else --COMPLETE-2-- COMPLETE-1: the user can give in a new date. I did it by simple calling the function again COMPLETE-2: the user can choose if he wants to enter a new. If not, all dates the user has put in should be put out as a calendar (a list of dates) -------- Original-Nachricht -------- > Datum: Thu, 11 Feb 2010 23:30:05 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Donnerstag 11 Februar 2010 23:04:01 schrieb kane96@gmx.de: > > but the exercise was nearly complete on the sheet and I just have to > > complete two parts and one of them is to ask the user if he want's to do > > more input. If so, I have to let him input a new value (triple) for > > MyDatatype, otherwise I have to print the list with all triples > > > > But to print it, you need to have a reference to the list of inputs. The > easiest way is to have it as a parameter in the worker loop. > > What *exactly* is your task? What is given and what are the specifications > for a solution? > > > > > > > Am Donnerstag 11 Februar 2010 22:34:45 schrieb kane96@gmx.de: > > > > the problem is the function should be > > > > readMyDatatype :: IO MyDatatype > > > > readMyDatatype = do ... > > > > Is it possible to do it somehow different without a parameter? > > > > > > Separate the worker from the API function. > > > > > > API: > > > > > > readMyDatatype :: IO MyDatatype > > > readMyDatatype = call worker with appropriate arguments > > > > > > worker: > > > > > > readMD :: t1 -> t2 -> ... -> tn -> IO MyDatatype -- Sicherer, schneller und einfacher. Die aktuellen Internet-Browser - jetzt kostenlos herunterladen! http://portal.gmx.net/de/go/atbrowser From legajid at free.fr Fri Feb 12 16:05:57 2010 From: legajid at free.fr (legajid) Date: Fri Feb 12 15:31:37 2010 Subject: [Haskell-beginners] Regular expressions in case Message-ID: <4B75C2B5.6030802@free.fr> Hi, is it possible to write regular expressions in case .. of ? I tried it, with no success. a x = case x of "a1" -> "A1" "a2" -> "A2" "a*" -> "A*" "b1" -> "B1" _ -> "_" for x="a3", result is _, instead of A* that i wanted. Thks, Didier From daniel.is.fischer at web.de Fri Feb 12 17:04:12 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Feb 12 16:37:10 2010 Subject: [Haskell-beginners] Regular expressions in case In-Reply-To: <4B75C2B5.6030802@free.fr> References: <4B75C2B5.6030802@free.fr> Message-ID: <201002122304.13117.daniel.is.fischer@web.de> Am Freitag 12 Februar 2010 22:05:57 schrieb legajid: > Hi, > is it possible to write regular expressions in case .. of ? > > I tried it, with no success. > > a x = > case x of > "a1" -> "A1" > "a2" -> "A2" > "a*" -> "A*" > "b1" -> "B1" > _ -> "_" > > > for x="a3", result is _, instead of A* that i wanted. > > Thks, > Didier No, case expressions use "pattern matching" as in http://haskell.org/onlinereport/exps.html#sect3.17 , that is, matching on constructors, not "pattern matching" as in matching a regex pattern. You can do a little like that with wildcard patterns, a x = case x of "a1" -> "A1" "a2" -> "A2" ('a':_) -> "A*" "b1" -> "B1" _ -> "_" in a simple case like the above. In more complicated situations, use a mix of pattern matching and guards, import Text.Regex.PCRE a' x = case x of "a1" -> "A1" ('a':rest) | rest =~ "[0-9]*" -> optAGen | cond1 rest -> opt1 | cond2 rest -> opt2 "b1" -> "B1" blah | blah =~ "[0-9]*" -> optNum _ -> defaultOption From daniel.is.fischer at web.de Fri Feb 12 17:18:06 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Feb 12 16:51:02 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100212191526.81280@gmx.net> References: <20100210205248.215170@gmx.net> <201002112330.05615.daniel.is.fischer@web.de> <20100212191526.81280@gmx.net> Message-ID: <201002122318.07158.daniel.is.fischer@web.de> Am Freitag 12 Februar 2010 20:15:26 schrieb kane96@gmx.de: > the exercise looks like that: > > readMyCal :: IO MyCalendar > readMyCal = do putStr "day: " > d <- readInt > putStr "month: " > m <- readMonth > putStr "year: " > y <- readInt > let mydate = (d,m,y) > if not (legalDate mydate) then > do putStrLn "wrong" > --COMPLETE-1-- > else > --COMPLETE-2-- > > COMPLETE-1: the user can give in a new date. I did it by simple calling > the function again Reasonable. > COMPLETE-2: the user can choose if he wants to enter > a new. If not, all dates the user has put in should be put out as a > calendar (a list of dates) > Okay, that's not nice. But since you have no global variables to store the list of dates entered in (yes, there are ways to have global variables, but it's not a good idea unless you really have to), call readMoreDates :: [MyDate] -> IO MyCaledar readMoreDates previous = do ... (code duplication where it isn't really necessary, but what the heck). From knyttv at gmail.com Sat Feb 13 10:48:04 2010 From: knyttv at gmail.com (=?utf-8?Q?Vojt=C4=9Bch_Knyttl?=) Date: Sat Feb 13 10:19:04 2010 Subject: [Haskell-beginners] running HGL on Mac OSX Message-ID: <158B6819-400F-4145-B833-F80A202DCCEA@gmail.com> Hello, I am having difficulties running HGL on Mac OSX, Snow Leopard. Here is what I've done: ?? 1. Installed X11 for OSX ("About" dialog says: The X Window System, XQuartz 2.3.4 (xorg-server 1.4.2-apple45)) ?? 2. Got X11 from Hackage ? configured, built and installed ? however, there where quite a lot of warnings: ? [ 8 of 25] Compiling Graphics.X11.Xlib.Color ( Graphics/X11/Xlib/Color.hs, dist/build/Graphics/X11/Xlib/Color.o ) Graphics/X11/Xlib/Color.hs:38:0: Warning: The import of `Foreign.C.Types' is redundant except perhaps to import instances from `Foreign.C.Types' To import instances alone, use: import Foreign.C.Types() [ 9 of 25] Compiling Graphics.X11.Xlib.Font ( dist/build/Graphics/X11/Xlib/Font.hs, dist/build/Graphics/X11/Xlib/Font.o ) Graphics/X11/Xlib/Font.hsc:167:1: Warning: A do-notation statement discarded a result of type CInt. Suppress this warning by saying "_ <- xTextExtents font_struct c_string (fromIntegral nchars) direction_return font_ascent_return font_descent_return overall_return", or by using the flag -fno-warn-unused-do-bind ? and so on. ?? 3. Got HGL package, built and installed with some warnings like: ? [ 1 of 27] Compiling Graphics.HGL.Internals.Flag ( Graphics/HGL/Internals/Flag.hs, dist/build/Graphics/HGL/Internals/Flag.o ) Graphics/HGL/Internals/Flag.hs:1:0: Warning: Module `Prelude' is deprecated: You are using the old package `base' version 3.x. Future GHC versions will not support base version 3.x. You should update your code to use the new base version 4.x. ? ?? Now, when I try to run simple program like: main = runGraphics $ withWindow_ "Hello World Window" (300, 200) $ \ w -> do drawInWindow w $ text (100, 100) "Hello World" drawInWindow w $ ellipse (100, 80) (200, 180) getKey w it says: $ ghci graphics.hs GHCi, version 6.12.1: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Ok, modules loaded: Main. Prelude Main> main Loading package syb-0.1.0.2 ... linking ... done. Loading package X11-1.5.0.0 ... can't load .so/.DLL for: X11 (dlopen(libX11.dylib, 9): image not found) Prelude Main> Just to precise, I have X11 running (it can be seen in the OSX dock) Thanks From rick at rickmurphy.org Sat Feb 13 15:29:55 2010 From: rick at rickmurphy.org (Rick Murphy) Date: Sat Feb 13 15:05:25 2010 Subject: [Haskell-beginners] distinguished types Message-ID: <4B770BC3.4050507@rickmurphy.org> Greetings and thanks in advance for all the great work on this list. Being new Haskell I hope someone could help me clarify the use of the term *distinguished type* in relation to Haskell 98 as well as confirm my understanding of the construction of a distinguished type in GHC. I understand from [1] that a distinguised type is defined as a type with only one non-bottom value and that value is in fact identical to the name of the type. [1] provides the unit type () as an example of a Haskell distinguished type. Would it be accurate to say that an approach to creating distinguished types in Haskell is to create data types with a single constructor whose name is identical to the data type name? More specifically, would > data F = F deriving (Show) create a distinguished type F in Haskell? I've searched the Haskell Report, but there's no indication that the report recognizes distinguished types. Is that true and if so why ? 1. http://okmij.org/ftp/Scheme/misc.html -- Rick cell: 703-201-9129 web: http://www.rickmurphy.org blog: http://phaneron.rickmurphy.org From felipe.lessa at gmail.com Sat Feb 13 16:03:20 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sat Feb 13 15:34:23 2010 Subject: [Haskell-beginners] distinguished types In-Reply-To: <4B770BC3.4050507@rickmurphy.org> References: <4B770BC3.4050507@rickmurphy.org> Message-ID: <20100213210320.GA6526@kira.casa> On Sat, Feb 13, 2010 at 03:29:55PM -0500, Rick Murphy wrote: > I understand from [1] that a distinguised type is defined as a type > with only one non-bottom value and that value is in fact identical > to the name of the type. [1] provides the unit type () as an example > of a Haskell distinguished type. > > Would it be accurate to say that an approach to creating > distinguished types in Haskell is to create data types with a single > constructor whose name is identical to the data type name? Well, I don't have not even one milliOleg. That said, I think he used "distinguished" to mean that it is a "curious" data type included in the language. Maybe he also meant that, at least in Haskell, the type may receive special notation (you can't say 'data () = ()'). HTH, -- Felipe. From stephen.tetley at gmail.com Sat Feb 13 16:11:38 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sat Feb 13 15:42:37 2010 Subject: [Haskell-beginners] distinguished types In-Reply-To: <4B770BC3.4050507@rickmurphy.org> References: <4B770BC3.4050507@rickmurphy.org> Message-ID: <5fdc56d71002131311g599792ay4ee56226f6d17bfa@mail.gmail.com> Hello Rick I suspect that in the context of Oleg's piece, a "distinguished type" is merely a type that can be distinguished rather than a common concept like say a "dynamic type" or a "sum type". As he mentions further some types can have only one value such as Haskell's unit type - (). I can't find a definition for "distinguished type" in any of the programming books I've checked: various Haskell ones, Pierce's TAPL, and and various Scheme ones - Friedman, Wand and Haynes's EoPL, Lisp in Small Pieces and Springer and Friedman's Scheme and the Art of Programming; nor from a few searches on the web. Best wishes Stephen On 13 February 2010 20:29, Rick Murphy wrote: > I understand from [1] that a distinguised type is defined as a type with > only one non-bottom value and that value is in fact identical to the name of > the type. [1] provides the unit type () as an example of a Haskell > distinguished type. From daniel.is.fischer at web.de Sat Feb 13 16:15:03 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Feb 13 15:48:03 2010 Subject: [Haskell-beginners] distinguished types In-Reply-To: <20100213210320.GA6526@kira.casa> References: <4B770BC3.4050507@rickmurphy.org> <20100213210320.GA6526@kira.casa> Message-ID: <201002132215.04194.daniel.is.fischer@web.de> Am Samstag 13 Februar 2010 22:03:20 schrieb Felipe Lessa: > On Sat, Feb 13, 2010 at 03:29:55PM -0500, Rick Murphy wrote: > > I understand from [1] that a distinguised type is defined as a type > > with only one non-bottom value and that value is in fact identical > > to the name of the type. [1] provides the unit type () as an example > > of a Haskell distinguished type. > > > > Would it be accurate to say that an approach to creating > > distinguished types in Haskell is to create data types with a single > > constructor whose name is identical to the data type name? > > Well, I don't have not even one milliOleg. I must confess, I don't know how much type-fu a milliOleg denotes. > That said, I think he used "distinguished" to mean that it is > a "curious" data type included in the language. Yep, "distinguished" as in "special" (often plays a role akin to void in C/Java). > Maybe he also meant that, at least in > Haskell, the type may receive special notation (you can't say > 'data () = ()'). > > HTH, > > -- > Felipe. From jeedward at yahoo.com Sat Feb 13 18:58:38 2010 From: jeedward at yahoo.com (John Edward) Date: Sat Feb 13 18:29:36 2010 Subject: [Haskell-beginners] Draft paper submission deadline is extended: MULTICONF-10, Orlando, USA Message-ID: <602524.31483.qm@web45901.mail.sp1.yahoo.com> It would be highly appreciated if you could share this announcement with your colleagues, students and individuals whose research is in computer science, computer engineering, information science and related areas. Draft paper submission deadline is extended: MULTICONF-10, Orlando, USA The 2010 multi-conference (MULTICONF-10) (website: http://www.promoteresearch.org) will be held during July 12-14, 2010 in Orlando, Florida, USA. The primary goal of MULTICONF is to promote research and developmental activities in computer science, information technology, control engineering, and related fields. Another goal is to promote the dissemination of research to a multidisciplinary audience and to facilitate communication among researchers, developers, practitioners in different fields.The following conferences are planned to be organized as part of MULTICONF-10. * International Conference on Artificial Intelligence and Pattern Recognition (AIPR-10) * International Conference on Automation, Robotics and Control Systems (ARCS-10) * International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-10) * International Conference on Computer Communications and Networks (CCN-10) * International Conference on Enterprise Information Systems and Web Technologies (EISWT-10) * International Conference on High Performance Computing Systems (HPCS-10) * International Conference on Information Security and Privacy (ISP-10) * International Conference on Image and Video Processing and Computer Vision (IVPCV-10) * International Conference on Software Engineering Theory and Practice (SETP-10) * International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-10) MULTICONF-10 will be held at Imperial Swan Hotel and Suites. It is a full-service resort that puts you in the middle of the fun! Located 1/2 block south of the famed International Drive, the hotel is just minutes from great entertainment like Walt Disney World? Resort, Universal Studios and Sea World Orlando. Guests can enjoy free scheduled transportation to these theme parks, as well as spacious accommodations, outdoor pools and on-site dining ? all situated on 10 tropically landscaped acres. Here, guests can experience a full-service resort with discount hotel pricing in Orlando. Please see the website http://www.promoteresearch.org for more details. Sincerely John Edward -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100213/67328d40/attachment-0001.html From korpios at korpios.com Sat Feb 13 22:39:46 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 13 22:10:43 2010 Subject: [Haskell-beginners] Calculating SHA1 hashes? Message-ID: I'm trying to figure out the best way to calculate SHA1 hashes for files using Haskell. There are several libraries I tried from Hackage, but they all seem to end up computing the hash far too slowly vs. OpenSSL. Some of the libraries seem to be FFI bindings to OpenSSL, but I haven't figured out how to efficiently feed these. (For instance, hopenssl consumes a [Word8], but I haven't figured out how to lazily produce that from a file; using "unpack" on a ByteString seems to end up much too slow.) I also tried mimicking nano-md5 by writing a "nano-sha1" that was largely a "replace the name of the digest function" hack job, but I couldn't manage to get that working. Is there a particular accepted way to generate hashes that I'm missing? From renick at gmail.com Sun Feb 14 05:22:52 2010 From: renick at gmail.com (Renick Bell) Date: Sun Feb 14 04:53:47 2010 Subject: [Haskell-beginners] getting memory usage to be constant when mixing wav files Message-ID: I've written a program that mixes wav files read in by hsndfile, and it does so with reasonably satisfactory performance using RTS options -A and -K. Unfortunately, it does not have constant memory usage. Profiling the program shows that almost all of the memory allocation comes down to the following two functions: the first which calculates and writes the values of individual indexes to the target array (longer), and the second which runs the first for all the indexes in the shorter array. addInBase :: IOCArray Int Double -> IOCArray Int Double -> (Int, Int) -> IO () addInBase longer shorter (!li,!si) = do x <- readArray longer li y <- readArray shorter si let result = x + y writeArray longer li result addIn :: IOCArray Int Double -> IOCArray Int Double -> Int -> Int -> Int -> IO () addIn longer shorter shorterBounds !li !si | si > shorterBounds = return () | si <= shorterBounds = addInBase longer shorter (li,si) >> addIn longer shorter shorterBounds (li+1) (si+1) Basically, the addIn function is called by mapM_ across a list of all of the occurrences of the input wav files. I've tried ! and seq in many different places and combinations, but I cannot get the memory usage constant. How can I achieve that? What technique or principle will show me more specifically what is not being evaluated so that I can avoid this trouble in the future? I have read the wiki pages on Strictness, Laziness, and Performance, but maybe I have not fully understood how to apply what is written there to this code. Any help is greatly appreciated. If you notice any other glaring mistakes or bad ideas in the code above, I'm interested in that as well. -- Renick Bell http://the3rd2nd.com From knyttv at gmail.com Sun Feb 14 05:28:30 2010 From: knyttv at gmail.com (=?utf-8?Q?Vojt=C4=9Bch_Knyttl?=) Date: Sun Feb 14 04:59:28 2010 Subject: [Haskell-beginners] running HGL on OSX Message-ID: Hello, I am having difficulties running HGL on Mac OSX, Snow Leopard. Here is what I've done: ?? 1. Installed X11 for OSX ("About" dialog says: The X Window System, XQuartz 2.3.4 (xorg-server 1.4.2-apple45)) ?? 2. Got X11 from Hackage ? configured, built and installed ? however, there where quite a lot of warnings: ? [ 8 of 25] Compiling Graphics.X11.Xlib.Color ( Graphics/X11/Xlib/Color.hs, dist/build/Graphics/X11/Xlib/Color.o ) Graphics/X11/Xlib/Color.hs:38:0: Warning: The import of `Foreign.C.Types' is redundant except perhaps to import instances from `Foreign.C.Types' To import instances alone, use: import Foreign.C.Types() [ 9 of 25] Compiling Graphics.X11.Xlib.Font ( dist/build/Graphics/X11/Xlib/Font.hs, dist/build/Graphics/X11/Xlib/Font.o ) Graphics/X11/Xlib/Font.hsc:167:1: Warning: A do-notation statement discarded a result of type CInt. Suppress this warning by saying "_ <- xTextExtents font_struct c_string (fromIntegral nchars) direction_return font_ascent_return font_descent_return overall_return", or by using the flag -fno-warn-unused-do-bind ? and so on. ?? 3. Got HGL package, built and installed with some warnings like: ? [ 1 of 27] Compiling Graphics.HGL.Internals.Flag ( Graphics/HGL/Internals/Flag.hs, dist/build/Graphics/HGL/Internals/Flag.o ) Graphics/HGL/Internals/Flag.hs:1:0: Warning: Module `Prelude' is deprecated: You are using the old package `base' version 3.x. Future GHC versions will not support base version 3.x. You should update your code to use the new base version 4.x. ? ?? Now, when I try to run simple program like: main = runGraphics $ withWindow_ "Hello World Window" (300, 200) $ \ w -> do drawInWindow w $ text (100, 100) "Hello World" drawInWindow w $ ellipse (100, 80) (200, 180) getKey w it says: $ ghci graphics.hs GHCi, version 6.12.1: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Ok, modules loaded: Main. Prelude Main> main Loading package syb-0.1.0.2 ... linking ... done. Loading package X11-1.5.0.0 ... can't load .so/.DLL for: X11 (dlopen(libX11.dylib, 9): image not found) Prelude Main> Just to precise, I have X11 running (it can be seen in the OSX dock) Thanks From felipe.lessa at gmail.com Sun Feb 14 06:18:49 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sun Feb 14 05:49:48 2010 Subject: [Haskell-beginners] getting memory usage to be constant when mixing wav files In-Reply-To: References: Message-ID: <20100214111849.GA20197@kira.casa> On Sun, Feb 14, 2010 at 07:22:52PM +0900, Renick Bell wrote: > addInBase :: IOCArray Int Double -> IOCArray Int Double -> (Int, Int) -> IO () > addInBase longer shorter (!li,!si) = do > x <- readArray longer li > y <- readArray shorter si > let result = x + y > writeArray longer li result > > addIn :: IOCArray Int Double -> IOCArray Int Double -> Int -> Int -> > Int -> IO () > addIn longer shorter shorterBounds !li !si > | si > shorterBounds = return () > | si <= shorterBounds = addInBase longer shorter (li,si) > >> addIn longer shorter shorterBounds (li+1) (si+1) These functions don't have any lazyness problem. They run in the IO monad which enforces execution order. > Basically, the addIn function is called by mapM_ across a list of all > of the occurrences of the input wav files. I'd guess that the mapM_ is where the problem lies in. If I understood correctly, you're doing something like (in pseudo-Haskell): do files <- mapM readFile filenames -- read files lazily mapM_ addIn files -- do something mapM_ writeFile files -- write files (strictly) In other words, I guess you're reading the files lazily, right? If that's the case, then mapM_ is your culprit. Each 'addIn' will force your inputs into memory. You hold a reference to them so you can save the results later, so after mapM_ has completed everything is in memory. The solution is simple for that pseudo-Haskell above: do mapM process filenames where process filename = readFile filename >>= addIn >>= writeFile In other words, read, process and write the files in one IO action. After the first 'process' finishes, every data is ready to be garbage collected. Of course you will still have those 'IOCArray's in memory during the 'process' call. -- Felipe. From john.moore54 at gmail.com Sun Feb 14 14:54:54 2010 From: john.moore54 at gmail.com (John Moore) Date: Sun Feb 14 14:25:50 2010 Subject: [Haskell-beginners] indentation Message-ID: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: test4.hs Type: application/octet-stream Size: 2659 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20100214/4186f99f/test4.obj From korpios at korpios.com Sun Feb 14 15:04:36 2010 From: korpios at korpios.com (Tom Tobin) Date: Sun Feb 14 14:35:32 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> Message-ID: On Sun, Feb 14, 2010 at 1:54 PM, John Moore wrote: > Hi all, > ???????? I must be doing something wrong with my tabs. Indeed you are: you're using them. :-) Searching for tab characters in your file reveals that it uses both tab characters and spaces mixed throughout. You should convert your file to use only spaces; this should resolve your indentation problems. From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 14 15:44:15 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 14 15:15:18 2010 Subject: [Haskell-beginners] Calculating SHA1 hashes? In-Reply-To: References: Message-ID: <4B78609F.6060908@blacksapphire.com> Tom, The way to lazily produce [Word8] from a file is to unpack a lazy ByteString, and you're right - it will generally be slow. I don't know of any obvious accepted way to do it. The fast way is to work with ByteStrings. The update' function in hopenssl almost does what you want: You could unwrap your ByteStrings into Ptr Word8 using code like this: import qualified Data.ByteString.Internal as BI import Foreign.ForeignPtr ... let (bsFPtr, bsOffset, bsLength) = BI.toForeignPtr bs withForeignPtr bsFPtr $ \bsPtr_ -> do let bsPtr = bsPtr_ `plusPtr` bsOffset update' digest (bsPtr, fromIntegral bsLength) I should also mention that lazy I/O has problems - it temporarily leaks file handles, and doesn't handle errors correctly. It is generally better read blocks using hGet from Data.ByteString. Steve Tom Tobin wrote: > I'm trying to figure out the best way to calculate SHA1 hashes for > files using Haskell. There are several libraries I tried from > Hackage, but they all seem to end up computing the hash far too slowly > vs. OpenSSL. Some of the libraries seem to be FFI bindings to > OpenSSL, but I haven't figured out how to efficiently feed these. > (For instance, hopenssl consumes a [Word8], but I haven't figured out > how to lazily produce that from a file; using "unpack" on a ByteString > seems to end up much too slow.) I also tried mimicking nano-md5 by > writing a "nano-sha1" that was largely a "replace the name of the > digest function" hack job, but I couldn't manage to get that working. > > Is there a particular accepted way to generate hashes that I'm missing? > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Sun Feb 14 15:20:23 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Feb 14 15:21:17 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> Message-ID: <201002142120.23557.daniel.is.fischer@web.de> Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: > Hi all, > I must be doing something wrong with my tabs. Because this > keeps telling me parse error. Can some one see if it is indentation. I'm > sending a file so as you'll be able to see what going on. If I copy it > here it can appear wrong the difference is with the Var expression. > > John First of all, *don't mix tabs and spaces for indentation* (best, don't use tabs at all). It's evalStep d (Var x) = case x of (Val a) ->case x of (Val b) ->(lookup x d) if (isJust m_e)then evalStep(lookup x d) else fail "Error in expression -- no definition for variable!" The "if ... " is aligned with (Val b), so GHC tries to parse it as a pattern. But if-expressions aren't patterns, so you get a parse error. But the code doesn't really make sense (and isn't well typed) anyway. You probably want something like evalStep d (Var x) = case lookup x d of Just e -> e Nothing -> error "Error in expression -- no definition for variable!" for that. From jrm8005 at gmail.com Sun Feb 14 16:30:27 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Sun Feb 14 16:01:22 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <201002142120.23557.daniel.is.fischer@web.de> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> Message-ID: <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> On Sun, Feb 14, 2010 at 3:20 PM, Daniel Fischer wrote: > Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: >> Hi all, >> ? ? ? ? ?I must be doing something wrong with my tabs. Because this >> keeps telling me parse error. Can some one see if it is indentation. I'm >> sending a file so as you'll be able to see what going on. If I copy it >> here it can appear wrong the difference is with the Var expression. >> >> John > > First of all, *don't mix tabs and spaces for indentation* (best, don't use > tabs at all). I find the latter a bit too restrictive, especially since I use a text editor that is a glorified version of ed. Hitting the spacebar 19 times is too much to ask of me. And as such, I am occasionally forced to do something when a tab doesn't get me past the word `where' or `let', but isn't that the majority of what Layout specifies? Is there a good answer for caveman programmers who like ed and tabs? > > It's > > evalStep d (Var x) > ? ? = case x of > ? ? ? ?(Val a) ->case x of > ? ? ? ? ?(Val b) ->(lookup x d) > ? ? ? ? ?if (isJust m_e)then > ? ? ? ? ? evalStep(lookup x d) > ? ? ? ? ? else > ? ? ? ? ? ?fail "Error in expression -- no definition for variable!" > > The "if ... " is aligned with (Val b), so GHC tries to parse it as a > pattern. But if-expressions aren't patterns, so you get a parse error. > > But the code doesn't really make sense (and isn't well typed) anyway. > You probably want something like > > evalStep d (Var x) > ? ?= case lookup x d of > ? ? ? ?Just e -> e > ? ? ? ?Nothing -> error "Error in expression -- no definition for > variable!" > > for that. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 14 16:46:12 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 14 16:17:11 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> Message-ID: <4B786F24.1010704@blacksapphire.com> Jorden, Cave persons such as yourself can use tabs as long as your tab size is 8 characters. This is "hard-coded" into the Haskell 98 specification. Steve Jorden Mauro wrote: >> First of all, *don't mix tabs and spaces for indentation* (best, don't use >> tabs at all). > > I find the latter a bit too restrictive, especially since I use a text > editor that is a glorified version of ed. Hitting the spacebar 19 > times is too much to ask of me. > > And as such, I am occasionally forced to do something when a tab > doesn't get me past the word `where' or `let', but isn't that the > majority of what Layout specifies? > > Is there a good answer for caveman programmers who like ed and tabs? From jrm8005 at gmail.com Sun Feb 14 17:05:13 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Sun Feb 14 16:36:06 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <4B786F24.1010704@blacksapphire.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <4B786F24.1010704@blacksapphire.com> Message-ID: <3aaafc131002141405wc622c44n5c36089690e82bd0@mail.gmail.com> On Sun, Feb 14, 2010 at 4:46 PM, Stephen Blackheath [to Haskell-Beginners] wrote: > Jorden, > > Cave persons such as yourself can use tabs as long as your tab size is 8 > characters. ?This is "hard-coded" into the Haskell 98 specification. > My editor, being made of sticks, some rocks, and the jawbone of an ass, just puts in a tab character. The graphical representation of a tab character expands from the insertion point to the nearest multiple of 8 characters, but that has no bearing on the file contents. Also, there are situations when a tab-boundary is not enough. What is the correct course of action here? Currently, I usually try to change the line to spaces, or if I'm lazy, I'll put spaces after tabs, which I don't feel good about. My editor knows enough to indent the next line the same amount. > > Steve > > Jorden Mauro wrote: >>> First of all, *don't mix tabs and spaces for indentation* (best, don't use >>> tabs at all). >> >> I find the latter a bit too restrictive, especially since I use a text >> editor that is a glorified version of ed. Hitting the spacebar 19 >> times is too much to ask of me. >> >> And as such, I am occasionally forced to do something when a tab >> doesn't get me past the word `where' or `let', but isn't that the >> majority of what Layout specifies? >> >> Is there a good answer for caveman programmers who like ed and tabs? > From daniel.is.fischer at web.de Sun Feb 14 17:04:49 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Feb 14 16:37:42 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> Message-ID: <201002142304.49446.daniel.is.fischer@web.de> Am Sonntag 14 Februar 2010 22:30:27 schrieb Jorden Mauro: > On Sun, Feb 14, 2010 at 3:20 PM, Daniel Fischer > > wrote: > > Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: > >> Hi all, > >> ? ? ? ? ?I must be doing something wrong with my tabs. Because this > >> keeps telling me parse error. Can some one see if it is indentation. > >> I'm sending a file so as you'll be able to see what going on. If I > >> copy it here it can appear wrong the difference is with the Var > >> expression. > >> > >> John > > > > First of all, *don't mix tabs and spaces for indentation* (best, don't > > use tabs at all). > > I find the latter a bit too restrictive, especially since I use a text > editor that is a glorified version of ed. Okay: Whyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy? Isn't there some editor which allows you to configure the tab settings but still is whatever-you-like-about-ed enough for you to use? > Hitting the spacebar 19 times is too much to ask of me. > > And as such, I am occasionally forced to do something when a tab > doesn't get me past the word `where' or `let', but isn't that the > majority of what Layout specifies? > > Is there a good answer for caveman programmers who like ed and tabs? > Never change your tab-width. From jrm8005 at gmail.com Sun Feb 14 17:09:43 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Sun Feb 14 16:40:37 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <201002142304.49446.daniel.is.fischer@web.de> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <201002142304.49446.daniel.is.fischer@web.de> Message-ID: <3aaafc131002141409h3302425dv62e83bd63ae0fd81@mail.gmail.com> On Sun, Feb 14, 2010 at 5:04 PM, Daniel Fischer wrote: > Am Sonntag 14 Februar 2010 22:30:27 schrieb Jorden Mauro: >> On Sun, Feb 14, 2010 at 3:20 PM, Daniel Fischer >> >> wrote: >> > Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: >> >> Hi all, >> >> ? ? ? ? ?I must be doing something wrong with my tabs. Because this >> >> keeps telling me parse error. Can some one see if it is indentation. >> >> I'm sending a file so as you'll be able to see what going on. If I >> >> copy it here it can appear wrong the difference is with the Var >> >> expression. >> >> >> >> John >> > >> > First of all, *don't mix tabs and spaces for indentation* (best, don't >> > use tabs at all). >> >> I find the latter a bit too restrictive, especially since I use a text >> editor that is a glorified version of ed. > > Okay: Whyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy? Structural regular expressions. My editor is almost context-free! (ok, a lame joke) I also believe DaVinci was right when he said `simplicity is the ultimate sophistication'. > > Isn't there some editor which allows you to configure the tab settings but > still is whatever-you-like-about-ed enough for you to use? Well... there's nothing quite like Sam. > >> Hitting the spacebar 19 times is too much to ask of me. >> >> And as such, I am occasionally forced to do something when a tab >> doesn't get me past the word `where' or `let', but isn't that the >> majority of what Layout specifies? >> >> Is there a good answer for caveman programmers who like ed and tabs? >> > Never change your tab-width. > I can't! From magnus at therning.org Sun Feb 14 18:00:05 2010 From: magnus at therning.org (Magnus Therning) Date: Sun Feb 14 17:31:10 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <3aaafc131002141405wc622c44n5c36089690e82bd0@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <4B786F24.1010704@blacksapphire.com> <3aaafc131002141405wc622c44n5c36089690e82bd0@mail.gmail.com> Message-ID: <4B788075.6020707@therning.org> On 14/02/10 22:05, Jorden Mauro wrote: > On Sun, Feb 14, 2010 at 4:46 PM, Stephen Blackheath [to > Haskell-Beginners] > wrote: >> Jorden, >> >> Cave persons such as yourself can use tabs as long as your tab size is 8 >> characters. This is "hard-coded" into the Haskell 98 specification. >> > > My editor, being made of sticks, some rocks, and the jawbone of an > ass, just puts in a tab character. The graphical representation of a > tab character expands from the insertion point to the nearest multiple > of 8 characters, but that has no bearing on the file contents. Sure it does, the bearing is that there's a tab character there. ;-) > Also, there are situations when a tab-boundary is not enough. What is the > correct course of action here? Other people have already suggested it: change editor. Please let us know if there is *any* good reason for anyone to be using such a limited editor in the 21st century. > Currently, I usually try to change the line to spaces, or if I'm lazy, > I'll put spaces after tabs, which I don't feel good about. My editor > knows enough to indent the next line the same amount. From this it sounds like you aren't using such a stone age editor after all. Are you sure you can't get it to also convert tabs to spaces? /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature Url : http://www.haskell.org/pipermail/beginners/attachments/20100214/71d6b90e/signature.bin From jrm8005 at gmail.com Sun Feb 14 18:44:42 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Sun Feb 14 18:15:53 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <4B788075.6020707@therning.org> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <4B786F24.1010704@blacksapphire.com> <3aaafc131002141405wc622c44n5c36089690e82bd0@mail.gmail.com> <4B788075.6020707@therning.org> Message-ID: <62602083-8F31-478F-B1C4-1F9B11E05140@gmail.com> On Feb 14, 2010, at 6:00 PM, Magnus Therning wrote: > On 14/02/10 22:05, Jorden Mauro wrote: >> On Sun, Feb 14, 2010 at 4:46 PM, Stephen Blackheath [to >> Haskell-Beginners] >> >> wrote: >>> Jorden, >>> >>> Cave persons such as yourself can use tabs as long as your tab >>> size is 8 >>> characters. This is "hard-coded" into the Haskell 98 specification. >>> >> >> My editor, being made of sticks, some rocks, and the jawbone of an >> ass, just puts in a tab character. The graphical representation of a >> tab character expands from the insertion point to the nearest >> multiple >> of 8 characters, but that has no bearing on the file contents. > > Sure it does, the bearing is that there's a tab character there. ;-) If I put one. > >> Also, there are situations when a tab-boundary is not enough. What >> is the >> correct course of action here? > > Other people have already suggested it: change editor. Not happening. Sam is sublime. > > Please let us know if there is *any* good reason for anyone to be > using such a > limited editor in the 21st century. Structural regexes. Size. Remote editing. Simplicity of code, UI, etc. Lack of bugs. Orthogonality. Performance. (Sam handles dozens of megabyte-sized files, even on a remote machine, without batting an eye, even during regex commands) > >> Currently, I usually try to change the line to spaces, or if I'm >> lazy, >> I'll put spaces after tabs, which I don't feel good about. My editor >> knows enough to indent the next line the same amount. > > From this it sounds like you aren't using such a stone age editor > after all. I assure you, I am. It has exactly only 33 commands. Give it a spin, I doubt you'll like it. It's not ed, but does have a GUI -- a verrry simple one. > Are you sure you can't get it to also convert tabs to spaces? Not without reprogramming it. Of course, I could convert files by hand, but I could just as easily use spaces. I just thought tabs were acceptable. I was a contientious objector in the Tabs or Spaces War. Is just using spaces the Haskell Caveman Solution? > > /M > > -- > Magnus Therning (OpenPGP: 0xAB4DFBA4) > magnus?therning?org Jabber: magnus?therning?org > http://therning.org/magnus identi.ca|twitter: magthe > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From byorgey at seas.upenn.edu Sun Feb 14 20:51:19 2010 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Sun Feb 14 20:22:13 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> Message-ID: <20100215015119.GA2966@seas.upenn.edu> On Sun, Feb 14, 2010 at 04:30:27PM -0500, Jorden Mauro wrote: > On Sun, Feb 14, 2010 at 3:20 PM, Daniel Fischer > wrote: > > Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: > >> Hi all, > >> ? ? ? ? ?I must be doing something wrong with my tabs. Because this > >> keeps telling me parse error. Can some one see if it is indentation. I'm > >> sending a file so as you'll be able to see what going on. If I copy it > >> here it can appear wrong the difference is with the Var expression. > >> > >> John > > > > First of all, *don't mix tabs and spaces for indentation* (best, don't use > > tabs at all). > > I find the latter a bit too restrictive, especially since I use a text > editor that is a glorified version of ed. Hitting the spacebar 19 > times is too much to ask of me. > > And as such, I am occasionally forced to do something when a tab > doesn't get me past the word `where' or `let', but isn't that the > majority of what Layout specifies? > > Is there a good answer for caveman programmers who like ed and tabs? Another good answer is to use explicit curly braces and semicolons so you don't have to rely on layout. -Brent From jrm8005 at gmail.com Sun Feb 14 21:57:05 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Sun Feb 14 21:27:59 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <20100215015119.GA2966@seas.upenn.edu> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <20100215015119.GA2966@seas.upenn.edu> Message-ID: <3aaafc131002141857w760606dbpafc3e0f671ed6cc2@mail.gmail.com> On Sun, Feb 14, 2010 at 8:51 PM, Brent Yorgey wrote: > On Sun, Feb 14, 2010 at 04:30:27PM -0500, Jorden Mauro wrote: >> On Sun, Feb 14, 2010 at 3:20 PM, Daniel Fischer >> wrote: >> > Am Sonntag 14 Februar 2010 20:54:54 schrieb John Moore: >> >> Hi all, >> >> ? ? ? ? ?I must be doing something wrong with my tabs. Because this >> >> keeps telling me parse error. Can some one see if it is indentation. I'm >> >> sending a file so as you'll be able to see what going on. If I copy it >> >> here it can appear wrong the difference is with the Var expression. >> >> >> >> John >> > >> > First of all, *don't mix tabs and spaces for indentation* (best, don't use >> > tabs at all). >> >> I find the latter a bit too restrictive, especially since I use a text >> editor that is a glorified version of ed. Hitting the spacebar 19 >> times is too much to ask of me. >> >> And as such, I am occasionally forced to do something when a tab >> doesn't get me past the word `where' or `let', but isn't that the >> majority of what Layout specifies? >> >> Is there a good answer for caveman programmers who like ed and tabs? > > Another good answer is to use explicit curly braces and semicolons so > you don't have to rely on layout. Yes, I am a recovering C programmer. You caught me! I really do appreciate the features of sam, and its simplicity is why I like layout. Omit needless punctuation, I say. > > -Brent > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From magnus at therning.org Mon Feb 15 05:30:57 2010 From: magnus at therning.org (Magnus Therning) Date: Mon Feb 15 05:01:51 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <62602083-8F31-478F-B1C4-1F9B11E05140@gmail.com> References: <4f7ad1ad1002141154p3c7e4562l4e3f042ffd797c4d@mail.gmail.com> <201002142120.23557.daniel.is.fischer@web.de> <3aaafc131002141330u3092908bl398b2ec651124e38@mail.gmail.com> <4B786F24.1010704@blacksapphire.com> <3aaafc131002141405wc622c44n5c36089690e82bd0@mail.gmail.com> <4B788075.6020707@therning.org> <62602083-8F31-478F-B1C4-1F9B11E05140@gmail.com> Message-ID: On Sun, Feb 14, 2010 at 23:44, Jorden Mauro wrote: > On Feb 14, 2010, at 6:00 PM, Magnus Therning wrote: >> Are you sure you can't get it to also convert tabs to spaces? > > Not without reprogramming it. Of course, I could convert files by hand, but > I could just as easily use spaces. I just thought tabs were acceptable. > > I was a contientious objector in the Tabs or Spaces War. Is just using > spaces the Haskell Caveman Solution? I'd argue the solution is to just use one. The issue is with mixing them! /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From bugspynet at gmail.com Mon Feb 15 06:33:35 2010 From: bugspynet at gmail.com (Gabi) Date: Mon Feb 15 06:04:28 2010 Subject: [Haskell-beginners] indentation Message-ID: <22d241861002150333m7609c47di9e129def6348638d@mail.gmail.com> BTW, is there some indent tool for Haskell. Something like "indent" command line tool for c? -- Regards, Gabi http://bugspy.net From magnus at therning.org Mon Feb 15 07:08:06 2010 From: magnus at therning.org (Magnus Therning) Date: Mon Feb 15 06:38:59 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <22d241861002150333m7609c47di9e129def6348638d@mail.gmail.com> References: <22d241861002150333m7609c47di9e129def6348638d@mail.gmail.com> Message-ID: On Mon, Feb 15, 2010 at 11:33, Gabi wrote: > BTW, is there some indent tool for Haskell. > Something like "indent" command line tool for c? Since indentation is significant (in most source files) I suspect it would be difficult to create an "indent"-like tool for Haskell. If you want modify indentation, e.g. switch from tabs to spaces, or change from 4 to 2 spaces then you can use any tool that lets you do a search and replace. /M -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From luca_ciciriello at hotmail.com Mon Feb 15 07:50:19 2010 From: luca_ciciriello at hotmail.com (Luca Ciciriello) Date: Mon Feb 15 07:21:13 2010 Subject: [Haskell-beginners] indentation In-Reply-To: <22d241861002150333m7609c47di9e129def6348638d@mail.gmail.com> References: <22d241861002150333m7609c47di9e129def6348638d@mail.gmail.com> Message-ID: On MacOS X I use Emacs (Aqua). This version of emacs supports the indentation utilities for Haskell. Anyway you can downloads this tool for any GNU emacs here: http://projects.haskell.org/haskellmode-emacs/ Bye. Luca. > Date: Mon, 15 Feb 2010 13:33:35 +0200 > From: bugspynet@gmail.com > To: beginners@haskell.org > Subject: [Haskell-beginners] indentation > > BTW, is there some indent tool for Haskell. > Something like "indent" command line tool for c? > > -- > Regards, > Gabi > > http://bugspy.net > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners _________________________________________________________________ Tell us your greatest, weirdest and funniest Hotmail stories http://clk.atdmt.com/UKM/go/195013117/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100215/3bb1710b/attachment.html From kg6y_ucd at yahoo.co.jp Mon Feb 15 10:44:51 2010 From: kg6y_ucd at yahoo.co.jp (Uchida Yasuo) Date: Mon Feb 15 10:15:47 2010 Subject: [Haskell-beginners] space leak Message-ID: <163175.19234.qm@web10510.mail.ogk.yahoo.co.jp> Hello, I came across the following space leak problem today. How can I fix this? (Tested on Mac OS X 10.5.8, GHC 6.10.3) -- test.hs module Main where import System import qualified Data.ByteString.Lazy.Char8 as L main = do args <- getArgs let n = read $ args !! 0 cs <- L.getContents let !a = L.take n cs mapM_ (print . L.length) $ L.lines cs print a -- gen.hs module Main where main = do putStrLn $ take 1000000 $ cycle "foo" main These are compiled with the following options: $ ghc --make -O2 test $ ghc --make -O2 gen The memory usage seems to depend on the argument(=17000) passed. On my MacBook(Core2 Duo 2.0GHz), 16000 works fine. $ ./gen | head -1000 | ./test 17000 +RTS -sstderr ... 3,793,673,564 bytes allocated in the heap 9,901,516 bytes copied during GC 635,576,092 bytes maximum residency (11 sample(s)) 248,725,136 bytes maximum slop 1759 MB total memory in use (562 MB lost due to fragmentation) Generation 0: 6941 collections, 0 parallel, 16.91s, 18.15s elapsed Generation 1: 11 collections, 0 parallel, 0.03s, 0.03s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 3.04s ( 27.64s elapsed) GC time 16.94s ( 18.18s elapsed) EXIT time 0.00s ( 0.01s elapsed) Total time 19.99s ( 45.82s elapsed) %GC time 84.8% (39.7% elapsed) Alloc rate 1,245,766,300 bytes per MUT second Productivity 15.2% of total user, 6.6% of total elapsed $ ./gen | head -1000 | ./test 16000 +RTS -sstderr ... 4,000,652,128 bytes allocated in the heap 7,428,180 bytes copied during GC 1,057,588 bytes maximum residency (1001 sample(s)) 525,092 bytes maximum slop 5 MB total memory in use (1 MB lost due to fragmentation) Generation 0: 6362 collections, 0 parallel, 0.10s, 0.12s elapsed Generation 1: 1001 collections, 0 parallel, 0.09s, 0.09s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 2.59s ( 23.26s elapsed) GC time 0.18s ( 0.22s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 2.77s ( 23.47s elapsed) %GC time 6.6% (0.9% elapsed) Alloc rate 1,545,246,968 bytes per MUT second Productivity 93.4% of total user, 11.0% of total elapsed -- Regards, Yasuo Uchida From daniel.is.fischer at web.de Mon Feb 15 12:07:16 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 15 11:40:11 2010 Subject: [Haskell-beginners] space leak In-Reply-To: <163175.19234.qm@web10510.mail.ogk.yahoo.co.jp> References: <163175.19234.qm@web10510.mail.ogk.yahoo.co.jp> Message-ID: <201002151807.17019.daniel.is.fischer@web.de> Am Montag 15 Februar 2010 16:44:51 schrieb Uchida Yasuo: > Hello, > > I came across the following space leak problem today. > How can I fix this? > (Tested on Mac OS X 10.5.8, GHC 6.10.3) > > -- test.hs > module Main where > > import System > import qualified Data.ByteString.Lazy.Char8 as L > > main = do args <- getArgs > let n = read $ args !! 0 > cs <- L.getContents > let !a = L.take n cs The problem is this. The Bang pattern does less than you probably think. The definition of lazy ByteStrings is data ByteString = Empty | Chunk {-# UNPACK #-} !S.ByteString ByteString , so when you write let !a = L.take n cs , you force the constructor (null cs ? Empty : Chunk start rest), Since cs is not empty, it's Chunk, and that forces the first part of the ByteString, which will be as long as the prefix which stdin immediately delivers, but at most the default chunk size (32K or 64K, normally [minus two words for bookkeeping]). If n is larger than a) the default chunk size or b) what L.getContents got immediately[*], a holds on to the (almost) entire input and you have a bad memory leak. Fix: force a to be completely evaluated, e.g. let !a = L.take n cs !l = L.length a By evaluating the length, a doesn't keep references to cs and all can be garbage collected. [*] how long the first chunk is, depends in this pipeline on scheduling, number of available cores/CPUs, OS buffer size. > mapM_ (print . L.length) $ L.lines cs > print a > > > -- gen.hs > module Main where > > main = do putStrLn $ take 1000000 $ cycle "foo" > main > > > These are compiled with the following options: > > $ ghc --make -O2 test > $ ghc --make -O2 gen > > The memory usage seems to depend on the argument(=17000) passed. > On my MacBook(Core2 Duo 2.0GHz), 16000 works fine. From kg6y_ucd at yahoo.co.jp Mon Feb 15 13:02:13 2010 From: kg6y_ucd at yahoo.co.jp (Uchida Yasuo) Date: Mon Feb 15 12:33:08 2010 Subject: [Haskell-beginners] space leak In-Reply-To: <201002151807.17019.daniel.is.fischer@web.de> Message-ID: <20100215180213.1133.qmail@web10503.mail.ogk.yahoo.co.jp> Oh, What a relief! Thank you for your clear explanation! --- Daniel Fischer wrote: > Am Montag 15 Februar 2010 16:44:51 schrieb Uchida Yasuo: > > Hello, > > > > I came across the following space leak problem today. > > How can I fix this? > > (Tested on Mac OS X 10.5.8, GHC 6.10.3) > > > > -- test.hs > > module Main where > > > > import System > > import qualified Data.ByteString.Lazy.Char8 as L > > > > main = do args <- getArgs > > let n = read $ args !! 0 > > cs <- L.getContents > > let !a = L.take n cs > > The problem is this. The Bang pattern does less than you probably think. > The definition of lazy ByteStrings is > > data ByteString = Empty | Chunk {-# UNPACK #-} !S.ByteString ByteString > > , so when you write > > let !a = L.take n cs > > , you force the constructor (null cs ? Empty : Chunk start rest), Since cs > is not empty, it's Chunk, and that forces the first part of the ByteString, > which will be as long as the prefix which stdin immediately delivers, but > at most the default chunk size (32K or 64K, normally [minus two words for > bookkeeping]). > > If n is larger than a) the default chunk size or b) what L.getContents got > immediately[*], a holds on to the (almost) entire input and you have a bad > memory leak. > > Fix: force a to be completely evaluated, e.g. > > let !a = L.take n cs > !l = L.length a > > By evaluating the length, a doesn't keep references to cs and all can be > garbage collected. > > [*] how long the first chunk is, depends in this pipeline on scheduling, > number of available cores/CPUs, OS buffer size. __ Regards, Yasuo Uchida From felipe.lessa at gmail.com Mon Feb 15 13:24:38 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Mon Feb 15 12:55:37 2010 Subject: [Haskell-beginners] space leak In-Reply-To: <163175.19234.qm@web10510.mail.ogk.yahoo.co.jp> References: <163175.19234.qm@web10510.mail.ogk.yahoo.co.jp> Message-ID: <20100215182438.GA21847@kira.casa> On Tue, Feb 16, 2010 at 12:44:51AM +0900, Uchida Yasuo wrote: > The memory usage seems to depend on the argument(=17000) passed. > On my MacBook(Core2 Duo 2.0GHz), 16000 works fine. The default chunk size for bytestring-0.9.1.5 is 32k [1]. I don't know why 16k is the magical number here. However, you strictly compute take. When the number of bytes you take is available in the first chunk, everything is done. If you need more then one chunk, then that bang patter ! will force only the *first* chunk, the others will be take'en lazily. You can try to verify this by using L.toChunks and noting how many chunks are being created. [1] http://hackage.haskell.org/packages/archive/bytestring/0.9.1.5/doc/html/src/Data-ByteString-Lazy-Internal.html#defaultChunkSize HTH, -- Felipe. From kg6y_ucd at yahoo.co.jp Mon Feb 15 17:42:03 2010 From: kg6y_ucd at yahoo.co.jp (Uchida Yasuo) Date: Mon Feb 15 17:12:59 2010 Subject: [Haskell-beginners] space leak In-Reply-To: <20100215182438.GA21847@kira.casa> Message-ID: <729469.4625.qm@web10514.mail.ogk.yahoo.co.jp> That's right! You solved the mystery of the magic number! --- Felipe Lessa wrote: > You can try to verify this by using L.toChunks and noting how > many chunks are being created. -- test.hs module Main where import System import System.IO import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Char8 as S main = do args <- getArgs let n = read $ args !! 0 cs <- L.getContents let !a = L.take n cs !l = L.length a hPutStrLn stderr $ "first chunk : " ++ show (S.length $ head $ L.toChunks cs) mapM_ (print . L.length) $ L.lines cs print a $ ./gen | head -1000 | ./test 17000 +RTS -sstderr > /dev/null ./test 17000 +RTS -sstderr first chunk : 16384 gen: : commitAndReleaseBuffer: resource vanished (Broken pipe) 4,085,671,308 bytes allocated in the heap 7,659,656 bytes copied during GC 1,091,072 bytes maximum residency (1001 sample(s)) 540,552 bytes maximum slop 5 MB total memory in use (1 MB lost due to fragmentation) Generation 0: 6507 collections, 0 parallel, 0.10s, 0.13s elapsed Generation 1: 1001 collections, 0 parallel, 0.09s, 0.10s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 2.62s ( 23.11s elapsed) GC time 0.19s ( 0.23s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 2.81s ( 23.34s elapsed) %GC time 6.8% (1.0% elapsed) Alloc rate 1,558,678,834 bytes per MUT second Productivity 93.2% of total user, 11.2% of total elapsed -- Regards, Yasuo Uchida From daniel.is.fischer at web.de Mon Feb 15 18:16:09 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 15 17:48:58 2010 Subject: [Haskell-beginners] space leak In-Reply-To: <729469.4625.qm@web10514.mail.ogk.yahoo.co.jp> References: <729469.4625.qm@web10514.mail.ogk.yahoo.co.jp> Message-ID: <201002160016.10156.daniel.is.fischer@web.de> Am Montag 15 Februar 2010 23:42:03 schrieb Uchida Yasuo: > That's right! You solved the mystery of the magic number! > > --- Felipe Lessa wrote: > > You can try to verify this by using L.toChunks and noting how > > many chunks are being created. > > $ ./gen | head -1000 | ./test 17000 +RTS -sstderr > /dev/null > ./test 17000 +RTS -sstderr > first chunk : 16384 It's not so easy, I get varying values: 4096, 8192, 32760, 28658, 16376, 12288, ... It may be different on other machines, but on my box, there's no hard "magic number", just a tendency to get 1xbuffer size or 2xbuffer size, or defaultChunkSize, the other values are rarer. > -- > Regards, > Yasuo Uchida From korpios at korpios.com Mon Feb 15 22:23:38 2010 From: korpios at korpios.com (Tom Tobin) Date: Mon Feb 15 21:54:30 2010 Subject: [Haskell-beginners] Equivalent of FOOLANGUAGEPATH environment variable? Message-ID: Is there an easy way to declare a particular directory as a location for finding Haskell modules, similar to PYTHONPATH and similar environment variables for other languages? The GHC_PACKAGE_PATH doesn't seem to be quite the same thing. There's the option of setting -iSOMEPATH in one's .ghci file, but that doesn't seem to allow declaring a relative path via ~ or $HOME, making it a bit of a pain to maintain separate versions of one's .ghci across different machines. From lazyswamp at gmail.com Mon Feb 15 06:26:58 2010 From: lazyswamp at gmail.com (Kwanghoon Choi) Date: Tue Feb 16 06:14:42 2010 Subject: [Haskell-beginners] Loading QuickCheck in GHCi. Message-ID: <2d44ccdd1002150326k68fa8957ubbf07cb526f0f0eb@mail.gmail.com> Dear All, Whenever I tried to load QuickCheck in GHCi, I met the following problem: Prelude> :l Test.QuickCheck : module `Test.QuickCheck' is a package module Failed, modules loaded: none. Test.QuickCheck seems to be a module anyway, bit it couldn't be loaded directly by issuing the command. I don't understand why. Thanks in advance. Kwanghoon PS. Of course, I installed QuickCheck-2.1.0.3, and I can use it when I load it by loading some haskell program having "import Test.QuickCheck". -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100215/bb490276/attachment.html From bayer at cpw.math.columbia.edu Tue Feb 16 08:25:40 2010 From: bayer at cpw.math.columbia.edu (Dave Bayer) Date: Tue Feb 16 07:56:30 2010 Subject: [Haskell-beginners] Loading QuickCheck in GHCi. In-Reply-To: <2d44ccdd1002150326k68fa8957ubbf07cb526f0f0eb@mail.gmail.com> References: <2d44ccdd1002150326k68fa8957ubbf07cb526f0f0eb@mail.gmail.com> Message-ID: <04594823-84E9-484B-9F89-7352140652F8@math.columbia.edu> Try :m Test.QuickCheck The GHC manual explains the difference between :l and :m. :l Data.Char gives me the same error, but :m Data.Char works. Same with other system packages. In general, when I have a problem I like to make it as big as I can, to see the shape of what's going wrong. Is Test.QuickCheck broken? Or am I using the wrong command in ghci? On Feb 15, 2010, at 6:26 AM, Kwanghoon Choi wrote: > Prelude> :l Test.QuickCheck From adrianadshead at yahoo.co.uk Wed Feb 17 07:22:39 2010 From: adrianadshead at yahoo.co.uk (Adrian Adshead) Date: Wed Feb 17 06:53:27 2010 Subject: [Haskell-beginners] Linux install walkthrough Message-ID: <316371.30668.qm@web29007.mail.ird.yahoo.com> What I am looking for is a HOWTO for installing haskell on linux, specifically aGHC 6.10.4 haskell-platform-2.0.2 on Centos 5.4 using Leksah as the IDE, and developinga wx application for running on linux and windows. If anyone could point me towardssomething like that showing libraries needed and hoops to jump through then that would be great. But if not here's a rant about the problems:- I read an article recently (from 2006 I think, so rather outdated) which was talking aboutwhy there were more problems with haskell on windows than with haskell on linux andthe conclusion said that it is because more people develop haskell on linux than onwindows. I thought great, I'd rather use linux anyway so I'll give it a try. What I found was a hugeheadache and not much to help out with any problems. My linux of choice is centos (I want stability over features) and I use the?first?CD onlyof the latest 5.4?to install a minimal system, then use yum to put on only what I need.That formula has worked well for many other systems I have set up, so that is whatI want to do again. I do that so all my systems start from the same place and I canscript the necessary install steps to get to a working system for whatever the purpose. I found the whole need to jump through so many hoops frustrating and rather a wasteof my time. The developers of the libraries are the people who know what you need torun their libraries so a little help from them wouldn't be missed. Comparing my headacheto the installation?of the?latest GHC 6.12.1 and cabal-install was a breeze mainly becauseof the?bootstrap.sh which does the heavy lifting for you. That would be nice in every library. If each library developer could include something like that which would install necessaryexternal libraries, preferably which could be called as a prerequisite in the Cabal installprocess, then it really would make a huge difference. So far I am finding haskell to be a wonderful language and am really enjoying learningit, but my experience compared to when I was looking at Erlang is that the benefits ofthe language are diminished by the?hassle?of the infrastructure around the platform. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100217/f7286580/attachment.html From stephen.tetley at gmail.com Wed Feb 17 08:04:19 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Wed Feb 17 07:35:06 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <316371.30668.qm@web29007.mail.ird.yahoo.com> References: <316371.30668.qm@web29007.mail.ird.yahoo.com> Message-ID: <5fdc56d71002170504x118f7dc7g53bc854ed150a68d@mail.gmail.com> Hi Adrian Is Centos close enough to RedHat to use Fedora packages? The Haskell-Platform seemingly is available as a package: https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig Leksah has a fairly large set of dependencies so installing it might take some work - particularly where it depends on packages outside the Haskell Plaform (GTK, etc...) you might well want versions from Hackage rather than ones prepackaged for Fedora. It might be worth asking on the Fedora-Haskell-devel mailing list for better advice. Best wishes Stephen From lakshminaras2002 at gmail.com Wed Feb 17 08:30:13 2010 From: lakshminaras2002 at gmail.com (Lakshmi Narasimhan) Date: Wed Feb 17 08:01:01 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <5fdc56d71002170504x118f7dc7g53bc854ed150a68d@mail.gmail.com> References: <316371.30668.qm@web29007.mail.ird.yahoo.com> <5fdc56d71002170504x118f7dc7g53bc854ed150a68d@mail.gmail.com> Message-ID: <3cca9ddb1002170530t2dc6201ftf64ab8fb914c354e@mail.gmail.com> Hi Adrian, Were you able to get the installation of Leksah done ? I haven't tried installing leksah from cabal in centos myself but it would be good to know whether it is possible to get leksah built without having to upgrade gtk and glib in Centos 5.4. In that case, we might be able to use some rpms from fedora haskell platform. On Wed, Feb 17, 2010 at 6:34 PM, Stephen Tetley wrote: > Hi Adrian > > Is Centos close enough to RedHat to use Fedora packages? > > The Haskell-Platform seemingly is available as a package: > > https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig > > Leksah has a fairly large set of dependencies so installing it might > take some work - particularly where it depends on packages outside the > Haskell Plaform (GTK, etc...) you might well want versions from > Hackage rather than ones prepackaged for Fedora. It might be worth > asking on the Fedora-Haskell-devel mailing list for better advice. > > Best wishes > > Stephen > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -- Regards Lakshmi Narasimhan T V -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100217/69cb131c/attachment-0001.html From adrianadshead at yahoo.co.uk Wed Feb 17 14:48:47 2010 From: adrianadshead at yahoo.co.uk (Adrian Adshead) Date: Wed Feb 17 14:19:33 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <3cca9ddb1002170530t2dc6201ftf64ab8fb914c354e@mail.gmail.com> Message-ID: <466290.4025.qm@web29020.mail.ird.yahoo.com> Hi Lakshmi, I've had two attempts at getting it going, the first I didn't get very far beforedeciding to give other, more up to date, linuxes a go, but had little luck onthat front. Next time around I got further but ran out of time. The problem isthat I want to spend my time writing software (and I have a windows systemup and running) not trying to fight to get the?system working. I really didn'tthink it would be too much to ask that a simple?install script would exist,or at least a HowTo for one of the more popular?linuxes (RedHat). I will have another look at it this weekend and see how far I get. If I manageto succeed I will document the process and post it to the wiki. Haskell seemsto be a?great language and there are lots of helpful people in the communitywho are willing to help newbies like myself get off the ground, but?when the'system' fights back as much as it does I'm not surprised that not?many peopleuse haskell, it's just easier to use something else. --- On Wed, 17/2/10, Lakshmi Narasimhan wrote: From: Lakshmi Narasimhan Subject: Re: [Haskell-beginners] Linux install walkthrough To: adrianadshead@yahoo.co.uk Cc: beginners@haskell.org Date: Wednesday, 17 February, 2010, 13:30 Hi Adrian, Were you able to get the installation of Leksah done ? I haven't tried installing leksah from cabal in centos myself but it would be good to know whether it is possible to get leksah built without having to upgrade gtk and glib in Centos 5.4. In that case, we might be able to use some rpms from fedora haskell platform. On Wed, Feb 17, 2010 at 6:34 PM, Stephen Tetley wrote: Hi Adrian Is Centos close enough to RedHat to use Fedora packages? The Haskell-Platform seemingly is available as a package: https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig Leksah has a fairly large set of dependencies so installing it might take some work - particularly where it depends on packages outside the Haskell Plaform (GTK, etc...) you might well want versions from Hackage rather than ones prepackaged for Fedora. It might be worth asking on the Fedora-Haskell-devel mailing list for better advice. Best wishes Stephen _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners -- Regards Lakshmi Narasimhan T V -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100217/ce6e48b4/attachment.html From mutilating.cauliflowers.stephen at blacksapphire.com Wed Feb 17 17:14:58 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Wed Feb 17 16:45:52 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <466290.4025.qm@web29020.mail.ird.yahoo.com> References: <466290.4025.qm@web29020.mail.ird.yahoo.com> Message-ID: <4B7C6A62.3090106@blacksapphire.com> Adrian, The Haskell Platform is still relatively new, and therefore binary support is not so good for Linux yet. But you don't actually lose much from what the Platform would give you if you use the GHC 6.10 binary releases from http://haskell.org/ghc/ The fact that this old-fashioned way works so well has also slowed adoption of the Platform on Linux. This worked nicely for me on Ubuntu before the Haskell Platform existed. Once GHC is installed, you then install cabal-install by hand using its bootstrap script. Add $HOME/.cabal/bin/ to your PATH, and then you can install any package easily with the 'cabal install' command. There is no essential difference between this setup and the Platform, except you start with fewer packages. Give that a try - You should find it works without fuss. I suggest you use 6.10 (not 6.12) as it's the most stable at present. There are two Linux binary variants - depending on what libraries are present on your system (one RedHat flavoured and one Debian flavoured). This is explained on the download page. Steve Adrian Adshead wrote: > Hi Lakshmi, > > I've had two attempts at getting it going, the first I didn't get very > far before > deciding to give other, more up to date, linuxes a go, but had little > luck on > that front. Next time around I got further but ran out of time. The > problem is > that I want to spend my time writing software (and I have a windows system > up and running) not trying to fight to get the system working. I really > didn't > think it would be too much to ask that a simple install script would exist, > or at least a HowTo for one of the more popular linuxes (RedHat). > > I will have another look at it this weekend and see how far I get. If I > manage > to succeed I will document the process and post it to the wiki. Haskell > seems > to be a great language and there are lots of helpful people in the community > who are willing to help newbies like myself get off the ground, but when the > 'system' fights back as much as it does I'm not surprised that not many > people > use haskell, it's just easier to use something else. > > --- On *Wed, 17/2/10, Lakshmi Narasimhan //* > wrote: > > > From: Lakshmi Narasimhan > Subject: Re: [Haskell-beginners] Linux install walkthrough > To: adrianadshead@yahoo.co.uk > Cc: beginners@haskell.org > Date: Wednesday, 17 February, 2010, 13:30 > > Hi Adrian, > > Were you able to get the installation of Leksah done ? I haven't > tried installing leksah from cabal in centos myself but it would be > good to know whether it is possible to get leksah built without > having to upgrade gtk and glib in Centos 5.4. In that case, we might > be able to use some rpms from fedora haskell platform. > > On Wed, Feb 17, 2010 at 6:34 PM, Stephen Tetley > > > wrote: > > Hi Adrian > > Is Centos close enough to RedHat to use Fedora packages? > > The Haskell-Platform seemingly is available as a package: > > https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig > > Leksah has a fairly large set of dependencies so installing it might > take some work - particularly where it depends on packages > outside the > Haskell Plaform (GTK, etc...) you might well want versions from > Hackage rather than ones prepackaged for Fedora. It might be worth > asking on the Fedora-Haskell-devel mailing list for better advice. > > Best wishes > > Stephen > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > > > > -- > Regards > Lakshmi Narasimhan T V > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From patrick.leboutillier at gmail.com Thu Feb 18 11:31:33 2010 From: patrick.leboutillier at gmail.com (Patrick LeBoutillier) Date: Thu Feb 18 11:02:16 2010 Subject: [Haskell-beginners] [OT] Haskell-inspired functions for BASH Message-ID: Hi all, I've been studying Haskell for about a year now, and I've really come to like it. In my daily work I write a lot of BASH shell scripts and I thought I'd try add some of the haskell features and constructs to BASH to make my scripting life a bit easier. So I've been working on a small BASH function library that implements some basic functional programming building blocks. Note: There is no actual Haskell code involved here. All this is very prototypical, but here is an example of some of the stuff I've got so far (map, filter, foldr): $ ls data 1.txt 2.txt # basic map, argument goes on the command line $ ls -d data/* | map basename 1.txt 2.txt # map with lambda expression $ ls -d data/* | map '\f -> basename $f .txt' 1 2 # simple filter, also works with lambda $ ls -d data/* | map basename | filter 'test 1.txt =' 1.txt # sum $ ls -d data/* | map '\f -> basename $f .txt' | foldr '\x acc -> echo $(($x + $acc))' 0 3 Before I continue with this project, I'm looking for a bit of feedback/info: - Does anyone know if there are already similar projets out there? - Does anyone find this interesting? - Any other comment/suggestion/feedback Thanks a lot, Patrick LeBoutillier -- ===================== Patrick LeBoutillier Rosem?re, Qu?bec, Canada From mcguire at crsr.net Thu Feb 18 11:46:27 2010 From: mcguire at crsr.net (Tommy M. McGuire) Date: Thu Feb 18 11:17:02 2010 Subject: [Haskell-beginners] [OT] Haskell-inspired functions for BASH In-Reply-To: References: Message-ID: <4B7D6EE3.4070004@crsr.net> Patrick LeBoutillier wrote: > Hi all, > > I've been studying Haskell for about a year now, and I've really come > to like it. In my daily work I write a lot of BASH shell scripts and I > thought I'd try add some of the haskell features and constructs to > BASH to make my scripting life a bit easier. So I've been working on a > small BASH function library that implements some basic functional > programming building blocks. > > Note: There is no actual Haskell code involved here. > > All this is very prototypical, but here is an example of some of the > stuff I've got so far (map, filter, foldr): > > $ ls data > 1.txt 2.txt > > # basic map, argument goes on the command line > $ ls -d data/* | map basename > 1.txt > 2.txt > > # map with lambda expression > $ ls -d data/* | map '\f -> basename $f .txt' > 1 > 2 > > # simple filter, also works with lambda > $ ls -d data/* | map basename | filter 'test 1.txt =' > 1.txt > > # sum > $ ls -d data/* | map '\f -> basename $f .txt' | foldr '\x acc -> echo > $(($x + $acc))' 0 > 3 > > > Before I continue with this project, I'm looking for a bit of feedback/info: > - Does anyone know if there are already similar projets out there? Once upon a time, there was the es shell, based on the Unix version of Tom Duff's Plan 9 rc shell, IIRC. It was intended to provide a functional language for shell programming. Never caught on at all, as far as I know, but it might be interesting. http://192.220.96.201/es/es-usenix-winter93.html Looks like there is a Google project for it: http://code.google.com/p/es-shell/ > - Does anyone find this interesting? Yep. :-) Looks pretty cool to me. > - Any other comment/suggestion/feedback -- Tommy M. McGuire mcguire@crsr.net From kane96 at gmx.de Thu Feb 18 18:25:18 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 18 17:56:03 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002122318.07158.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002112330.05615.daniel.is.fischer@web.de> <20100212191526.81280@gmx.net> <201002122318.07158.daniel.is.fischer@web.de> Message-ID: <20100218232518.21630@gmx.net> ok, now I did it by just calling from the original function by to a new one with an empty list at the beginning. How can I add the date at the end of the list? By creating a new list from the new date and using concat or is there a simpler way? -------- Original-Nachricht -------- > Datum: Fri, 12 Feb 2010 23:18:06 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Freitag 12 Februar 2010 20:15:26 schrieb kane96@gmx.de: > > the exercise looks like that: > > > > readMyCal :: IO MyCalendar > > readMyCal = do putStr "day: " > > d <- readInt > > putStr "month: " > > m <- readMonth > > putStr "year: " > > y <- readInt > > let mydate = (d,m,y) > > if not (legalDate mydate) then > > do putStrLn "wrong" > > --COMPLETE-1-- > > else > > --COMPLETE-2-- > > > > COMPLETE-1: the user can give in a new date. I did it by simple calling > > the function again > > Reasonable. > > > COMPLETE-2: the user can choose if he wants to enter > > a new. If not, all dates the user has put in should be put out as a > > calendar (a list of dates) > > > > Okay, that's not nice. But since you have no global variables to store the > list of dates entered in (yes, there are ways to have global variables, > but > it's not a good idea unless you really have to), call > > readMoreDates :: [MyDate] -> IO MyCaledar > readMoreDates previous = do ... > > (code duplication where it isn't really necessary, but what the heck). -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Thu Feb 18 18:41:56 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Thu Feb 18 18:14:37 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100218232518.21630@gmx.net> References: <20100210205248.215170@gmx.net> <201002122318.07158.daniel.is.fischer@web.de> <20100218232518.21630@gmx.net> Message-ID: <201002190041.56670.daniel.is.fischer@web.de> Am Freitag 19 Februar 2010 00:25:18 schrieb kane96@gmx.de: > ok, now I did it by just calling from the original function by to a new > one with an empty list at the beginning. > > How can I add the date at the end of the list? By creating a new list > from the new date and using concat or is there a simpler way? > Better stick it to the front by (:) and reverse the list just before printing. From kane96 at gmx.de Thu Feb 18 19:54:05 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Thu Feb 18 19:24:49 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <201002190041.56670.daniel.is.fischer@web.de> References: <20100210205248.215170@gmx.net> <201002122318.07158.daniel.is.fischer@web.de> <20100218232518.21630@gmx.net> <201002190041.56670.daniel.is.fischer@web.de> Message-ID: <20100219005405.21640@gmx.net> ok, looks much easier and works :) But what are now the correct signatures for the function? Normally the "one and only" function should be: readCal :: IO Calendar My function are: readCal = readCal2 datelist and: readCal2 datelist = do... which returns the Calendar (the list of dates) -------- Original-Nachricht -------- > Datum: Fri, 19 Feb 2010 00:41:56 +0100 > Von: Daniel Fischer > An: kane96@gmx.de > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > Am Freitag 19 Februar 2010 00:25:18 schrieb kane96@gmx.de: > > ok, now I did it by just calling from the original function by to a new > > one with an empty list at the beginning. > > > > How can I add the date at the end of the list? By creating a new list > > from the new date and using concat or is there a simpler way? > > > > Better stick it to the front by (:) and reverse the list just before > printing. -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From jao at gnu.org Thu Feb 18 20:13:11 2010 From: jao at gnu.org (Jose A. Ortega Ruiz) Date: Thu Feb 18 20:39:08 2010 Subject: [Haskell-beginners] ffi woes Message-ID: <87ocjmxc2g.fsf@newton.homeunix.net> Hi, Show below is a short program using the FFI to access libiw and provide, given an interface name such as "wlan0" the associated ESSID. One uses iw_get_basic_config to fill a struct wireless_config (dynamically allocated), and extract from that the desired string, which is a field of type char[MAX_ESSID_LEN] in said struct type. When i run this program (or call getWirelessInfo inside ghci) with an existing network interface, it segfaults (calling it with a non-existent one returns the expected empty string, so the problem is after the first 'if' in getWirelessInfo): can anybody spot what am i doing wrong? Or perhaps give me any hint on how to debug the issue? TIA! jao {-# LANGUAGE CPP, ForeignFunctionInterface #-} module Main (main) where import System.Environment import Foreign import Foreign.C.Types import Foreign.C.String #include foreign import ccall "iwlib.h iw_sockets_open" c_iw_open :: IO CInt foreign import ccall "unistd.h close" c_iw_close :: CInt -> IO () -- the 3rd argument is a struct wireless_config*, an input parameter foreign import ccall "iwlib.h iw_get_basic_config" c_iw_basic_config :: CInt -> CString -> Ptr () -> IO CInt -- Given a network interface name, return its ESSID getWirelessInfo :: String -> IO String getWirelessInfo iface = allocaBytes (#size struct wireless_config) $ \wc -> withCString iface $ \istr -> do i <- c_iw_open r <- c_iw_basic_config i istr wc c_iw_close i if (r < 0) then return "" else do hase <- (#peek struct wireless_config, has_essid) wc :: IO CInt eon <- (#peek struct wireless_config, essid_on) wc :: IO CInt if hase > 0 && eon > 0 then do l <- (#peek struct wireless_config, essid_len) wc e <- (#peek struct wireless_config, essid) wc -- wireless_config.essid is a char[MAX_LEN] peekCStringLen (e, fromIntegral (l :: CInt)) else return "" main = (fmap head getArgs) >>= getWirelessInfo >>= print From marco-oweber at gmx.de Thu Feb 18 22:31:47 2010 From: marco-oweber at gmx.de (Marc Weber) Date: Thu Feb 18 22:02:31 2010 Subject: [Haskell-beginners] [OT] Haskell-inspired functions for BASH In-Reply-To: References: Message-ID: <1266548909-sup-4644@nixos> Your project is nice. I never thougt about how much effort it is to write cmd | while read f; do basename $f; done cmd | map basename *is* much easier. For now I just put map(){ while read l; do $@ "$l"; done; } into my .bashrc. Having a simple parser which parses the "lambda" funtion to split cols could be interesting. Example ecoh -e "a b\nb c" | map "\1 2 -> echo $2" should output the second col or such. (separating values by spaces or tabs. There are at least two tools which can do this as well: | awk '{ print $2}': or such or man col. Probably there are more tools. The Windows-Powershell even let's you pass objects. However it's command line interface is horrible compared to bash / zsh. But I think they're working on this. Also you could use some Vim tools to workaround this. There was another attempt to create many tools using Haskell. I don't recall the name. Just open hackage and search for "Shell". On the other hand let me tell you what my experience is. I do shell scripting once in a while. However bash/sh sucks if you have to do more complicated things. It can be done but you start fighting with the language or learning details about it you don't want to know. Eg the difference echo "foo" | while ... done in contrast to while ... done <<< "foo" The first one opens a subshell which means if you assign local vars you can't use the results outside of the loop. So additionally to your attempt I highly recommend you learning a scripting language such as Ruby or Python to get some things done. Why do I *not* recommend haskell here? Because compiling scripts will use much disk space (Haskell applications tend to be big) and ghci startup time is bad compared to either Python or Ruby. So you can image than you have to wait 5secs using a pipe like this: echa | app1 | app2 | app3 | app4 just because ghci has to startup and load some libraries. Anyway there are many projects which could server your needs. Eg http://www.focusresearch.com/gregor/sw/psh/ yet another. Before spending much effort on your library I'd spend some time searching the net to see what is available.. Also make sure to search the haskell-cafe mailinglist. I think you'll find some pointers there as well. Whil searching the web don't miss autopager (FireFox plugin). Good luck and thank you for your map shortcut idea! Marc Weber From marcmigge at googlemail.com Wed Feb 17 16:07:12 2010 From: marcmigge at googlemail.com (Marc D. Migge) Date: Fri Feb 19 01:52:12 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <466290.4025.qm@web29020.mail.ird.yahoo.com> References: <466290.4025.qm@web29020.mail.ird.yahoo.com> Message-ID: <4B7C5A80.2040909@gmail.com> Hi, maybe you can be a little more specific, as to what problems you ran into? I just installed Leksah on Ubuntu via "cabal install" and (using the proper constraints) it worked like a charm. Install info for Leksah is here: http://www.haskell.org/haskellwiki/Leksah_Installation I didn't bother to install the haskell-platform though. Up to now I could get all the packages I needed from the Ubuntu repos or Hackage without problems. Best regards, Marc Adrian Adshead wrote: > Hi Lakshmi, > I've had two attempts at getting it going, the first I didn't get very far beforedeciding to give other, more up to date, linuxes a go, but had little luck onthat front. Next time around I got further but ran out of time. The problem isthat I want to spend my time writing software (and I have a windows systemup and running) not trying to fight to get the system working. I really didn'tthink it would be too much to ask that a simple install script would exist,or at least a HowTo for one of the more popular linuxes (RedHat). > I will have another look at it this weekend and see how far I get. If I manageto succeed I will document the process and post it to the wiki. Haskell seemsto be a great language and there are lots of helpful people in the communitywho are willing to help newbies like myself get off the ground, but when the'system' fights back as much as it does I'm not surprised that not many peopleuse haskell, it's just easier to use something else. > --- On Wed, 17/2/10, Lakshmi Narasimhan wrote: > > From: Lakshmi Narasimhan > Subject: Re: [Haskell-beginners] Linux install walkthrough > To: adrianadshead@yahoo.co.uk > Cc: beginners@haskell.org > Date: Wednesday, 17 February, 2010, 13:30 > > Hi Adrian, > > Were you able to get the installation of Leksah done ? I haven't tried installing leksah from cabal in centos myself but it would be good to know whether it is possible to get leksah built without having to upgrade gtk and glib in Centos 5.4. In that case, we might be able to use some rpms from fedora haskell platform. > > > On Wed, Feb 17, 2010 at 6:34 PM, Stephen Tetley wrote: > > Hi Adrian > > > > Is Centos close enough to RedHat to use Fedora packages? > > > > The Haskell-Platform seemingly is available as a package: > > > > https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig > > > > Leksah has a fairly large set of dependencies so installing it might > > take some work - particularly where it depends on packages outside the > > Haskell Plaform (GTK, etc...) you might well want versions from > > Hackage rather than ones prepackaged for Fedora. It might be worth > > asking on the Fedora-Haskell-devel mailing list for better advice. > > > > Best wishes > > > > Stephen > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From stephen.tetley at gmail.com Fri Feb 19 06:39:39 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Feb 19 06:10:20 2010 Subject: [Haskell-beginners] ffi woes In-Reply-To: <87ocjmxc2g.fsf@newton.homeunix.net> References: <87ocjmxc2g.fsf@newton.homeunix.net> Message-ID: <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> Hello Jose Looking at the source for iwlib.h the wireless_config struct doesn't have an essid_len field, at least in this version which seems to be current one: * Version : 22 16.3.07 That said, if you are using this version then hsc2hs (the FFI preprocessor) should be throwing an error along the lines of error: structure has no member named 'essid_len' What command line flags are you using to compile? Best wishes Stephen From jon at ffconsultancy.com Fri Feb 19 14:57:50 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Fri Feb 19 13:12:42 2010 Subject: [Haskell-beginners] Decent Haskell REPL? Message-ID: <201002191957.50704.jon@ffconsultancy.com> GHCI seems to require type definitions to be described in a separate file and then loaded into the REPL, which is seriously tedious. Are there any Haskell REPLs that don't have such limitations and, preferably, use JIT compilation instead of an interpreter? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From korpios at korpios.com Fri Feb 19 13:46:30 2010 From: korpios at korpios.com (Tom Tobin) Date: Fri Feb 19 13:17:11 2010 Subject: [Haskell-beginners] Decent Haskell REPL? In-Reply-To: <201002191957.50704.jon@ffconsultancy.com> References: <201002191957.50704.jon@ffconsultancy.com> Message-ID: On Fri, Feb 19, 2010 at 1:57 PM, Jon Harrop wrote: > > GHCI seems to require type definitions to be described in a separate file and > then loaded into the REPL, which is seriously tedious. > > Are there any Haskell REPLs that don't have such limitations and, preferably, > use JIT compilation instead of an interpreter? I run Haskell in an inferior shell in Emacs alongside haskell-mode; it's easy to get immediate feedback to my changes that way. From jao at gnu.org Fri Feb 19 13:28:34 2010 From: jao at gnu.org (Jose A. Ortega Ruiz) Date: Fri Feb 19 13:39:06 2010 Subject: [Haskell-beginners] Re: ffi woes References: <87ocjmxc2g.fsf@newton.homeunix.net> <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> Message-ID: <877hq9xep9.fsf@newton.homeunix.net> Hi Stephen, Stephen Tetley writes: > Hello Jose > > > Looking at the source for iwlib.h the wireless_config struct doesn't > have an essid_len field, at least in this version which seems to be > current one: > > * Version : 22 16.3.07 > > That said, if you are using this version then hsc2hs (the FFI > preprocessor) should be throwing an error along the lines of > > error: structure has no member named 'essid_len' I'm using the iwlib.h that comes with debian's libiw-dev package, which claims to be version 30 9.4 of wireless tools (it's not clear to me to what version of libiw that corresponds). At any rate, the iwlib.h in my system defines a wireless_config struct with an essid_len (and hsc2hs is thus not complaining). If i try to read the string from essid using peekCString i also get a segfault. > What command line flags are you using to compile? i do a plain 'hsc2hs Wireless.hsc' and then either 'ghci -liw Wireless.hs' (to try interactively) or 'ghc -o wire -liw Wireless.hs'. I've also tried adding -O, but the results are the same. Thanks a lot for your help, jao From freiksenet at gmail.com Fri Feb 19 15:07:19 2010 From: freiksenet at gmail.com (Mikhail Novikov) Date: Fri Feb 19 14:38:08 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell Message-ID: <4B7EEF77.3010004@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello! Four days ago I decided to try to learn Haskell by participating in Google AI Challenge (http://csclub.uwaterloo.ca/contest/). I went with LYAH and Real-World Haskell and I had no problems with functional core of Haskell, as I have lispy background. The problems begun when I tried to move my code to use different kind of decision algorithms, like negascout or flood fill. I have found a ready made solution for negascout (http://hackage.haskell.org/packages/archive/game-tree/0.1.0.0/doc/html/src/Data-Tree-Game_tree-Negascout.html), but I was quite shocked by it's complexity, especially considering the relative easy of imperative algorithm.(http://en.wikipedia.org/wiki/Negascout). IMHO it is just TOO extremely complex and hard to read :/ In flood fill situation is similar - I need to track all the colored squares among 4 lines of recursion and I couldn't find a reasonable way to do it without going to infinite recursion or having lots of duplicates. So basically, I wonder if there is some generic way to transfer imperative algorithms with local state to functional style without making them overly complex. Thanks a lot, Mikhail -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkt+73cACgkQPHyh4sfuKrl7NgCeKHrIdJbHrSse6z7eRrmAi6ck yYoAoIRJZLq6RVUcCG2Zf5Xc5tRW5YBk =oUX7 -----END PGP SIGNATURE----- From kane96 at gmx.de Fri Feb 19 15:24:15 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Feb 19 14:54:57 2010 Subject: [Haskell-beginners] foldr for Nats In-Reply-To: <20100204205845.26700@gmx.net> References: <20100126105245.288430@gmx.net> <5fdc56d71001260305h3a55380bv78e2732d68976708@mail.gmail.com> <20100201202048.41080@gmx.net> <5fdc56d71002011356t48e592cp91a7ff8cc1e4bef7@mail.gmail.com> <20100204205845.26700@gmx.net> Message-ID: <20100219202415.312080@gmx.net> nobody here, who can tell me how it can work? -------- Original-Nachricht -------- > Datum: Thu, 04 Feb 2010 21:58:45 +0100 > Von: kane96@gmx.de > An: Stephen Tetley , Daniel Fischer > CC: Beginners@haskell.org > Betreff: Re: [Haskell-beginners] foldr for Nats > @Stephan thanks for the code so far. > @Daniel it should look like foldrNat a b S(S(S(S(Z)))) gives a(a(a(a(b)))) > > > The thing is the definition have to be > -------- Original-Nachricht -------- > > Datum: Mon, 1 Feb 2010 21:56:14 +0000 > > Von: Stephen Tetley > > An: kane96@gmx.de > > CC: Beginners@haskell.org > > Betreff: Re: [Haskell-beginners] foldr for Nats > > > Hello > > > > I'm suspecting this isn't homework as you've waited a week so would > > presumably have missed a deadline. > > > > As Daniel Fischer wrote, one view of folds is that they replace the > > constructors of a data type, code follows... > > > > > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > > > > > -- Look at the type of foldr... > > > > -- *GHCi> :t foldr > > -- foldr :: (a -> b -> b) -> b -> [a] -> b > > > > -- It has 2 'constructor replacements': > > -- (a -> b -> b) & b > > > > -- Replacing Z is easy, we can get some code to compile > > -- by avoiding the hard bit with a wildcard pattern "_"... > > > > foldrNat1 :: unknown -> b -> Nat -> b > > foldrNat1 _ b Z = b > > > > -- What to do about the constructor (S ..) takes a bit more > > -- thought or at least some experimenting. I'll do the later... > > > > -- One thing to try, is to simply translate foldr with as few > > -- changes as possible: > > > > -- foldr :: (a -> b -> b) -> b -> [a] -> b > > -- foldr _ z [] = z > > -- foldr f z (x:xs) = f x (foldr f z xs) > > > > -- Unfortunately this leads to a problem: > > > > foldrNat2 :: (Nat -> b -> b) -> b -> Nat -> b > > foldrNat2 f b Z = b -- Z case is the same as before > > foldrNat2 f b (S n) = f undefined (foldrNat2 f b n) -- Arggh! undefined > > > > -- undefined is useful for prototyping, but its a real > > -- problem for running code! > > > > -- Actually I had another problem as well... > > -- > > -- The difference between Nat and [a] is that List 'carries' some data > > -- therefore (Nat -> b -> b) on Nat is not equivalent to (a -> b -> b) > > -- on [a]. > > > > -- So rather than change the type signature first, get rid of the > > -- undefined and see what happens > > > > foldrNat3 f b Z = b > > foldrNat3 f b (S n) = f (foldrNat3 f b n) > > > > -- *GHCi> :t foldrNat3 > > -- > (t -> t) -> t -> Nat -> t > > > > -- GHCi likes to call type variables t, but the signature is equal to > > > > -- foldrNat3 :: (b -> b) -> b -> Nat -> b > > > > > > -- This looks promising - it typechecks! > > -- So try a test: > > > > fromNat :: Nat -> Int > > fromNat n = foldrNat3 (+1) 0 n > > > > demo1 = fromNat (S (S (S Z))) -- 3 ?? > > > > -- By experimenting we seem to have a good answer, > > -- other people might prefer a more rigorous proof though. > > -- > NEU: Mit GMX DSL ?ber 1000,- ? sparen! > http://portal.gmx.net/de/go/dsl02 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From marcmigge at gmx.net Fri Feb 19 16:11:11 2010 From: marcmigge at gmx.net (Marc Dominik Migge) Date: Fri Feb 19 15:41:52 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <4B7EEF77.3010004@gmail.com> References: <4B7EEF77.3010004@gmail.com> Message-ID: <41c888ff1002191311o42a5ed42v9af45ff090131308@mail.gmail.com> Hi, I recommend you read John Hughe's article "Why Functional Programming Matters"[1]. As one of his examples he implements alpha-beta-pruning. I'm not really a Haskell expert, but I think the main difference will be in the kind of data structures you use to implement the algorithms. Many people have recommended Chris Okasaki's PhD thesis [2] to me for an in-depth treatment of the topic. [1]: http://www.cs.chalmers.se/~rjmh/Papers/whyfp.html [2]: http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf Best regards, Marc On Fri, Feb 19, 2010 at 9:07 PM, Mikhail Novikov wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello! > > Four days ago I decided to try to learn Haskell by participating in Google > AI Challenge (http://csclub.uwaterloo.ca/contest/). I went with LYAH and > Real-World Haskell and I had no problems with functional core of Haskell, as > I have lispy background. The problems begun when I tried to move my code to > use different kind of decision algorithms, like negascout or flood fill. > > I have found a ready made solution for negascout ( > http://hackage.haskell.org/packages/archive/game-tree/0.1.0.0/doc/html/src/Data-Tree-Game_tree-Negascout.html), > but I was quite shocked by it's complexity, especially considering the > relative easy of imperative algorithm.( > http://en.wikipedia.org/wiki/Negascout). IMHO it is just TOO extremely > complex and hard to read :/ > > In flood fill situation is similar - I need to track all the colored > squares among 4 lines of recursion and I couldn't find a reasonable way to > do it without going to infinite recursion or having lots of duplicates. > > So basically, I wonder if there is some generic way to transfer imperative > algorithms with local state to functional style without making them overly > complex. > > Thanks a lot, Mikhail > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.10 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ > > iEYEARECAAYFAkt+73cACgkQPHyh4sfuKrl7NgCeKHrIdJbHrSse6z7eRrmAi6ck > yYoAoIRJZLq6RVUcCG2Zf5Xc5tRW5YBk > =oUX7 > -----END PGP SIGNATURE----- > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100219/953fc6d0/attachment.html From kane96 at gmx.de Fri Feb 19 16:13:00 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Fri Feb 19 15:43:42 2010 Subject: [Haskell-beginners] consing an element to a list inside a file In-Reply-To: <20100219005405.21640@gmx.net> References: <20100210205248.215170@gmx.net> <201002122318.07158.daniel.is.fischer@web.de> <20100218232518.21630@gmx.net> <201002190041.56670.daniel.is.fischer@web.de> <20100219005405.21640@gmx.net> Message-ID: <20100219211300.312080@gmx.net> I checked it by using :t readCal :: IO Calendar and readCal2 :: Calendar -> IO Calendar so the function to call (readCal) is what it should be. thanks! -------- Original-Nachricht -------- > Datum: Fri, 19 Feb 2010 01:54:05 +0100 > Von: kane96@gmx.de > An: Daniel Fischer > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] consing an element to a list inside a file > ok, looks much easier and works :) > > But what are now the correct signatures for the function? Normally the > "one and only" function should be: readCal :: IO Calendar > My function are: readCal = readCal2 datelist > and: readCal2 datelist = do... which returns the Calendar (the list of > dates) > > > -------- Original-Nachricht -------- > > Datum: Fri, 19 Feb 2010 00:41:56 +0100 > > Von: Daniel Fischer > > An: kane96@gmx.de > > CC: beginners@haskell.org > > Betreff: Re: [Haskell-beginners] consing an element to a list inside a > file > > > Am Freitag 19 Februar 2010 00:25:18 schrieb kane96@gmx.de: > > > ok, now I did it by just calling from the original function by to a > new > > > one with an empty list at the beginning. > > > > > > How can I add the date at the end of the list? By creating a new list > > > from the new date and using concat or is there a simpler way? > > > > > > > Better stick it to the front by (:) and reverse the list just before > > printing. > > -- > NEU: Mit GMX DSL ?ber 1000,- ? sparen! > http://portal.gmx.net/de/go/dsl02 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From freiksenet at gmail.com Fri Feb 19 16:16:22 2010 From: freiksenet at gmail.com (Mikhail Novikov) Date: Fri Feb 19 15:47:11 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <41c888ff1002191307v2a359be8w4188d73c2581351f@mail.gmail.com> References: <4B7EEF77.3010004@gmail.com> <41c888ff1002191307v2a359be8w4188d73c2581351f@mail.gmail.com> Message-ID: <4B7EFFA6.4020400@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello! Thanks, I'll take a look. I was going to buy Okasaki's book for a very long time, probably I should finally do it :) Best regards, Mikhail On 02/19/2010 11:07 PM, Marc Dominik Migge wrote: > Hi, > > I recommend you read John Hughe's article "Why Functional Programming > Matters"[1]. As one of his examples he implements alpha-beta-pruning. I'm > not really a Haskell expert, but I think the main difference will be in the > kind of data structures you use to implement the algorithms. Many people > have recommended Chris Okasaki's PhD thesis [2] to me for an in-depth > treatment of the topic. > > [1]: http://www.cs.chalmers.se/~rjmh/Papers/whyfp.html > [2]: http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf > > Best regards, > Marc > > > On Fri, Feb 19, 2010 at 9:07 PM, Mikhail Novikov wrote: > > Hello! > > Four days ago I decided to try to learn Haskell by participating in Google > AI Challenge (http://csclub.uwaterloo.ca/contest/). I went with LYAH and > Real-World Haskell and I had no problems with functional core of Haskell, as > I have lispy background. The problems begun when I tried to move my code to > use different kind of decision algorithms, like negascout or flood fill. > > I have found a ready made solution for negascout ( > http://hackage.haskell.org/packages/archive/game-tree/0.1.0.0/doc/html/src/Data-Tree-Game_tree-Negascout.html), > but I was quite shocked by it's complexity, especially considering the > relative easy of imperative algorithm.( > http://en.wikipedia.org/wiki/Negascout). IMHO it is just TOO extremely > complex and hard to read :/ > > In flood fill situation is similar - I need to track all the colored > squares among 4 lines of recursion and I couldn't find a reasonable way to > do it without going to infinite recursion or having lots of duplicates. > > So basically, I wonder if there is some generic way to transfer imperative > algorithms with local state to functional style without making them overly > complex. > > Thanks a lot, Mikhail _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners >> -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkt+/6YACgkQPHyh4sfuKrkrdgCfaH4/z1RrQX33dtoO1QXWQshl LBUAn18H9/MdMjbGzeTJZ9+bxVYs5tfJ =9ZhZ -----END PGP SIGNATURE----- From felipe.lessa at gmail.com Fri Feb 19 16:18:59 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Fri Feb 19 15:49:43 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <4B7EEF77.3010004@gmail.com> References: <4B7EEF77.3010004@gmail.com> Message-ID: <20100219211859.GA5386@kira.casa> On Fri, Feb 19, 2010 at 10:07:19PM +0200, Mikhail Novikov wrote: > So basically, I wonder if there is some generic way to transfer > imperative algorithms with local state to functional style > without making them overly complex. It may be worthwhile to not translate at all. ST monad works as a charm :). Haskell is one of the best imperative languages. -- Felipe. From stephen.tetley at gmail.com Fri Feb 19 16:28:36 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Feb 19 15:59:16 2010 Subject: [Haskell-beginners] Re: ffi woes In-Reply-To: <877hq9xep9.fsf@newton.homeunix.net> References: <87ocjmxc2g.fsf@newton.homeunix.net> <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> <877hq9xep9.fsf@newton.homeunix.net> Message-ID: <5fdc56d71002191328t10cc3540td724a30471de8f71@mail.gmail.com> Hi I think I've found a version 30 from Debian's archive - the essid string is fixed length, rather than sized by essid_len (even though essid_len is now in the struct). Is this the same as the version you have? /* Structure for storing all wireless information for each device * This is a cut down version of the one above, containing only * the things *truly* needed to configure a card. * Don't add other junk, I'll remove it... */ typedef struct wireless_config { char name[IFNAMSIZ + 1]; /* Wireless/protocol name */ int has_nwid; iwparam nwid; /* Network ID */ int has_freq; double freq; /* Frequency/channel */ int freq_flags; int has_key; unsigned char key[IW_ENCODING_TOKEN_MAX]; /* Encoding key used */ int key_size; /* Number of bytes */ int key_flags; /* Various flags */ int has_essid; int essid_on; char essid[IW_ESSID_MAX_SIZE + 2]; /* ESSID (extended network) */ int essid_len; int has_mode; int mode; /* Operation mode */ } wireless_config; Best wishes Stephen From freiksenet at gmail.com Fri Feb 19 17:10:59 2010 From: freiksenet at gmail.com (Mikhail Novikov) Date: Fri Feb 19 16:41:43 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <20100219211859.GA5386@kira.casa> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> Message-ID: <4B7F0C73.50506@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello! Maybe I should look into ST monad for this. :) I am still interested if there is a way to make this kind of functions in purely functional way. Best regards, Mikhail On 02/19/2010 11:18 PM, Felipe Lessa wrote: > On Fri, Feb 19, 2010 at 10:07:19PM +0200, Mikhail Novikov wrote: >> So basically, I wonder if there is some generic way to transfer >> imperative algorithms with local state to functional style >> without making them overly complex. > > It may be worthwhile to not translate at all. ST monad works as > a charm :). Haskell is one of the best imperative languages. > > -- > Felipe. > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkt/DHMACgkQPHyh4sfuKrlfBQCfdnN8qaHmP1B2YPqVqifwTAAU HLgAnih0r81xjOOmd7SYDWPjOWZ75YaK =5pBO -----END PGP SIGNATURE----- From korpios at korpios.com Fri Feb 19 17:17:37 2010 From: korpios at korpios.com (Tom Tobin) Date: Fri Feb 19 16:48:17 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <4B7F0C73.50506@gmail.com> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> Message-ID: On Fri, Feb 19, 2010 at 4:10 PM, Mikhail Novikov wrote: > Maybe I should look into ST monad for this. :) I am still interested if there is a way to make this kind of functions in purely functional way. I *think* the answer to your question is "no". You can write imperative code in Haskell (via ST and IO), and you can write functional code that gets equivalent results to a given chunk of imperative code, but you can't directly translate imperative code to functional code, since they're two qualitatively different things. It's like asking to express a square in terms of a circle -- you can come up with a circle that has the same area, but it's definitely *not* a square. :-) From stephen.tetley at gmail.com Fri Feb 19 18:06:57 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Fri Feb 19 17:37:37 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> Message-ID: <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> Hello all Particularly concerning the negascout algorithm, there doesn't seem to be much in the algorithm presented on Wikipedia that couldn't be done purely functionally with a fairly equivalent line count (might need a auxiliary tree type and a tree fold). The 'imperativeness' in this case only seems to be assignment to accumulators. The version on Hackage doesn't seem to define an actual tree data type only a tree-like type class, which while making things general does appear to make things complicated. Best wishes Stephen From jao at gnu.org Fri Feb 19 17:15:18 2010 From: jao at gnu.org (Jose A. Ortega Ruiz) Date: Fri Feb 19 17:38:55 2010 Subject: [Haskell-beginners] Re: ffi woes References: <87ocjmxc2g.fsf@newton.homeunix.net> <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> <877hq9xep9.fsf@newton.homeunix.net> <5fdc56d71002191328t10cc3540td724a30471de8f71@mail.gmail.com> Message-ID: <873a0wyirt.fsf@newton.homeunix.net> Stephen Tetley writes: > Hi > > I think I've found a version 30 from Debian's archive - the essid > string is fixed length, rather than sized by essid_len (even though > essid_len is now in the struct). Is this the same as the version you > have? Yes, it is. I've tried to read the essid field both using peekCString, as in s <- (#peek struct wireless_info, essid) peekCString s and providing explicitly the maximum length of essid (34) to peekCStringLen. Do you mean that for a struct field that is a of type char[LEN] those peek functions are innappropriate? (I've checked using C that essid_len actually gets the correct value, and that the contents of essid is null-terminated, i.e. wi.essid[wi.essid_len] == '\0' is always true). Thanks, jao > > > /* Structure for storing all wireless information for each device > * This is a cut down version of the one above, containing only > * the things *truly* needed to configure a card. > * Don't add other junk, I'll remove it... */ > typedef struct wireless_config > { > char name[IFNAMSIZ + 1]; /* Wireless/protocol name */ > int has_nwid; > iwparam nwid; /* Network ID */ > int has_freq; > double freq; /* Frequency/channel */ > int freq_flags; > int has_key; > unsigned char key[IW_ENCODING_TOKEN_MAX]; /* Encoding key used */ > int key_size; /* Number of bytes */ > int key_flags; /* Various flags */ > int has_essid; > int essid_on; > char essid[IW_ESSID_MAX_SIZE + 2]; /* ESSID (extended network) */ > int essid_len; > int has_mode; > int mode; /* Operation mode */ > } wireless_config; > > Best wishes > > Stephen From adrianadshead at yahoo.co.uk Fri Feb 19 21:22:26 2010 From: adrianadshead at yahoo.co.uk (Adrian Adshead) Date: Fri Feb 19 20:53:07 2010 Subject: [Haskell-beginners] Linux install walkthrough In-Reply-To: <3cca9ddb1002170530t2dc6201ftf64ab8fb914c354e@mail.gmail.com> Message-ID: <202259.19669.qm@web29018.mail.ird.yahoo.com> I had another go at getting it going. leksah 0.6.1 requires gtk2hs >= 0.10gtk2hs 0.10.1 requires gtksourceview >= 2.2gtksourceview 2.2 requires gtk+ >= 2.12gtk+ >=2.12 requires upgraded glib So the answer is no, it is not installable on Centos withoutupgrade to gtk and glib. The fedora 12 install works and I have leksah and my wx appworking, but unfortunately I use NX to open a remote sessionto the server and leksah does something to crash the connection,so I can?not use it anyway. Adrian. --- On Wed, 17/2/10, Lakshmi Narasimhan wrote: From: Lakshmi Narasimhan Subject: Re: [Haskell-beginners] Linux install walkthrough To: adrianadshead@yahoo.co.uk Cc: beginners@haskell.org Date: Wednesday, 17 February, 2010, 13:30 Hi Adrian, Were you able to get the installation of Leksah done ? I haven't tried installing leksah from cabal in centos myself but it would be good to know whether it is possible to get leksah built without having to upgrade gtk and glib in Centos 5.4. In that case, we might be able to use some rpms from fedora haskell platform. On Wed, Feb 17, 2010 at 6:34 PM, Stephen Tetley wrote: Hi Adrian Is Centos close enough to RedHat to use Fedora packages? The Haskell-Platform seemingly is available as a package: https://admin.fedoraproject.org/pkgdb/users/packages/haskell-sig Leksah has a fairly large set of dependencies so installing it might take some work - particularly where it depends on packages outside the Haskell Plaform (GTK, etc...) you might well want versions from Hackage rather than ones prepackaged for Fedora. It might be worth asking on the Fedora-Haskell-devel mailing list for better advice. Best wishes Stephen _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners -- Regards Lakshmi Narasimhan T V -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100219/1ec6b4b4/attachment.html From heringtonlacey at mindspring.com Sat Feb 20 03:04:42 2010 From: heringtonlacey at mindspring.com (Dean Herington) Date: Sat Feb 20 02:35:28 2010 Subject: [Haskell-beginners] Re: ffi woes In-Reply-To: <873a0wyirt.fsf@newton.homeunix.net> References: <87ocjmxc2g.fsf@newton.homeunix.net> <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> <877hq9xep9.fsf@newton.homeunix.net> <5fdc56d71002191328t10cc3540td724a30471de8f71@mail.gmail.com> <873a0wyirt.fsf@newton.homeunix.net> Message-ID: At 11:15 PM +0100 2/19/10, Jose A. Ortega Ruiz wrote: >Stephen Tetley writes: > >> Hi >> >> I think I've found a version 30 from Debian's archive - the essid >> string is fixed length, rather than sized by essid_len (even though >> essid_len is now in the struct). Is this the same as the version you >> have? > >Yes, it is. I've tried to read the essid field both using peekCString, >as in > > s <- (#peek struct wireless_info, essid) > peekCString s > >and providing explicitly the maximum length of essid (34) to >peekCStringLen. Do you mean that for a struct field that is a of type >char[LEN] those peek functions are innappropriate? > >(I've checked using C that essid_len actually gets the correct value, >and that the contents of essid is null-terminated, i.e. >wi.essid[wi.essid_len] == '\0' is always true). > >Thanks, >jao > >> >> >> /* Structure for storing all wireless information for each device >> * This is a cut down version of the one above, containing only >> * the things *truly* needed to configure a card. >> * Don't add other junk, I'll remove it... */ >> typedef struct wireless_config >> { >> char name[IFNAMSIZ + 1]; /* Wireless/protocol name */ >> int has_nwid; >> iwparam nwid; /* Network ID */ >> int has_freq; >> double freq; /* Frequency/channel */ >> int freq_flags; >> int has_key; >> unsigned char key[IW_ENCODING_TOKEN_MAX]; /* Encoding key used */ >> int key_size; /* Number of bytes */ >> int key_flags; /* Various flags */ >> int has_essid; >> int essid_on; >> char essid[IW_ESSID_MAX_SIZE + 2]; /* ESSID >>(extended network) */ >> int essid_len; >> int has_mode; >> int mode; /* Operation mode */ >> } wireless_config; >> >> Best wishes >> > > Stephen Though I'm not an FFI expert, I'll take a stab in case it might help you. It seems to me that > s <- (#peek struct wireless_info, essid) > peekCString s would read a pointer from the essid field, which is clearly not what you want. I think you'd want to use #ptr. Maybe something like the following (untested!): l <- (#peek struct wireless_config, essid_len) wc p <- (#ptr struct wireless_info, essid) wc -- wireless_config.essid is a char[MAX_LEN] peekCStringLen (p, fromIntegral (l :: CInt)) Dean From jao at gnu.org Sat Feb 20 04:10:26 2010 From: jao at gnu.org (Jose A. Ortega Ruiz) Date: Sat Feb 20 04:39:02 2010 Subject: [Haskell-beginners] Re: ffi woes References: <87ocjmxc2g.fsf@newton.homeunix.net> <5fdc56d71002190339w59cd7130l35e875827193ac30@mail.gmail.com> <877hq9xep9.fsf@newton.homeunix.net> <5fdc56d71002191328t10cc3540td724a30471de8f71@mail.gmail.com> <873a0wyirt.fsf@newton.homeunix.net> Message-ID: <87y6iow9vh.fsf@newton.homeunix.net> Hi Dean, Dean Herington writes: [...] > Though I'm not an FFI expert, I'll take a stab in case it might help you. > > It seems to me that > >> s <- (#peek struct wireless_info, essid) >> peekCString s > > would read a pointer from the essid field, which is clearly not what > you want. I think you'd want to use #ptr. Maybe something like the > following (untested!): > > l <- (#peek struct wireless_config, essid_len) wc > p <- (#ptr struct wireless_info, essid) wc > -- wireless_config.essid is a char[MAX_LEN] > peekCStringLen (p, fromIntegral (l :: CInt)) > Right, using #ptr works (with the minor modification that it doesn't return its value inside IO, so one must use let p =..., instead of p <- ...). Thanks a lot for your help. Cheers, jao From kane96 at gmx.de Sat Feb 20 06:39:30 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Sat Feb 20 06:10:09 2010 Subject: [Haskell-beginners] list of integers to list of nats Message-ID: <20100220113930.284290@gmx.net> Hi, I have to write a function which maps a list of integers to a list of the corresponding nats. The following code is already there: data Nat = Z | S Nat deriving (Eq,Ord,Show) instance Enum Nat where toEnum i | i < 0 = error "Enum_Nat.toEnum: Negative integer" | i == 0 = Z | otherwise = S (toEnum (i-1)) the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))] how can I do that? -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From jon at ffconsultancy.com Sat Feb 20 10:31:31 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Feb 20 08:46:13 2010 Subject: [Haskell-beginners] Decent Haskell REPL? In-Reply-To: References: <201002191957.50704.jon@ffconsultancy.com> Message-ID: <201002201531.31170.jon@ffconsultancy.com> On Friday 19 February 2010 18:46:30 Tom Tobin wrote: > On Fri, Feb 19, 2010 at 1:57 PM, Jon Harrop wrote: > > GHCI seems to require type definitions to be described in a separate file > > and then loaded into the REPL, which is seriously tedious. > > > > Are there any Haskell REPLs that don't have such limitations and, > > preferably, use JIT compilation instead of an interpreter? > > I run Haskell in an inferior shell in Emacs alongside haskell-mode; > it's easy to get immediate feedback to my changes that way. What's your procedure for getting ghci to interpret a type definition? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From Christian.Maeder at dfki.de Sat Feb 20 09:59:52 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Sat Feb 20 09:30:31 2010 Subject: [Haskell-beginners] Re: list of integers to list of nats In-Reply-To: <20100220113930.284290@gmx.net> References: <20100220113930.284290@gmx.net> Message-ID: <4B7FF8E8.9040307@dfki.de> kane96@gmx.de schrieb: > Hi, > I have to write a function which maps a list of integers to a list of the corresponding nats. The following code is already there: > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > instance Enum Nat where > toEnum i | i < 0 = error "Enum_Nat.toEnum: Negative integer" > | i == 0 = Z > | otherwise = S (toEnum (i-1)) > > the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] > so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))] Since the result type is "Maybe [Nat]" the result should be: Just [S (S Z), Z, S Z, S (S (S Z))] I suppose the result should be Nothing if the input list contains any negative integer. > how can I do that? Who is your instructor? The most basic approach is do pattern-match on the input list. mapIntsToNats l = case l of [] -> ... h : t -> ... and call "mapIntsToNats" recursively on the tail "t". The recursive result is (also) of type "Maybe [Nat]", therefore you have to further pattern-match this result and insert the converted head element "h". Is this enough to help you? C. From Christian.Maeder at dfki.de Sat Feb 20 10:21:55 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Sat Feb 20 09:52:33 2010 Subject: [Haskell-beginners] Re: list of integers to list of nats In-Reply-To: <20100220113930.284290@gmx.net> References: <20100220113930.284290@gmx.net> Message-ID: <4B7FFE13.4040708@dfki.de> kane96@gmx.de schrieb: > Hi, > I have to write a function which maps a list of integers to a list of the corresponding nats. The following code is already there: > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > instance Enum Nat where > toEnum i | i < 0 = error "Enum_Nat.toEnum: Negative integer" > | i == 0 = Z > | otherwise = S (toEnum (i-1)) this function has type "Int -> Nat" and should be wrapped into a function of type "Int -> Maybe Nat" that does not produce a runtime error if called with negative input. > the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] > so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))] > > how can I do that? Have you heard about monads and mapM? (The type constructor Maybe is an instance of the class Monad.) Cheers Christian From Christian.Maeder at dfki.de Sat Feb 20 10:28:27 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Sat Feb 20 09:59:06 2010 Subject: [Haskell-beginners] Re: Decent Haskell REPL? In-Reply-To: <201002201531.31170.jon@ffconsultancy.com> References: <201002191957.50704.jon@ffconsultancy.com> <201002201531.31170.jon@ffconsultancy.com> Message-ID: <4B7FFF9B.2040903@dfki.de> Jon Harrop schrieb: > On Friday 19 February 2010 18:46:30 Tom Tobin wrote: >> On Fri, Feb 19, 2010 at 1:57 PM, Jon Harrop wrote: >>> GHCI seems to require type definitions to be described in a separate file >>> and then loaded into the REPL, which is seriously tedious. >>> >>> Are there any Haskell REPLs that don't have such limitations and, >>> preferably, use JIT compilation instead of an interpreter? >> I run Haskell in an inferior shell in Emacs alongside haskell-mode; >> it's easy to get immediate feedback to my changes that way. > > What's your procedure for getting ghci to interpret a type definition? > Typing ":r" to reload the currently loaded but later changed or extended file. C. From Christian.Maeder at dfki.de Sat Feb 20 10:31:32 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Sat Feb 20 10:02:09 2010 Subject: [Haskell-beginners] Re: Decent Haskell REPL? In-Reply-To: <201002201531.31170.jon@ffconsultancy.com> References: <201002191957.50704.jon@ffconsultancy.com> <201002201531.31170.jon@ffconsultancy.com> Message-ID: <4B800054.2000401@dfki.de> Jon Harrop schrieb: > On Friday 19 February 2010 18:46:30 Tom Tobin wrote: >> On Fri, Feb 19, 2010 at 1:57 PM, Jon Harrop wrote: >>> GHCI seems to require type definitions to be described in a separate file >>> and then loaded into the REPL, which is seriously tedious. >>> >>> Are there any Haskell REPLs that don't have such limitations and, >>> preferably, use JIT compilation instead of an interpreter? >> I run Haskell in an inferior shell in Emacs alongside haskell-mode; >> it's easy to get immediate feedback to my changes that way. > > What's your procedure for getting ghci to interpret a type definition? In other words: it does not work without a file to introduce types, but I don't think that's a problem. C. From korpios at korpios.com Sat Feb 20 11:19:28 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 20 10:50:05 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> Message-ID: On Fri, Feb 19, 2010 at 4:17 PM, Tom Tobin wrote: > It's like asking to express a square in terms of a circle -- you can > come up with a circle that has the same area Heh, it was pointed out to me that you actually *can't* do this: http://en.wikipedia.org/wiki/Squaring_the_circle You can get a circle that has *approximately* the same area, but never exactly. Curse my lack of math background! ^_^ From korpios at korpios.com Sat Feb 20 11:33:30 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 20 11:04:09 2010 Subject: [Haskell-beginners] Decent Haskell REPL? In-Reply-To: <201002201531.31170.jon@ffconsultancy.com> References: <201002191957.50704.jon@ffconsultancy.com> <201002201531.31170.jon@ffconsultancy.com> Message-ID: On Sat, Feb 20, 2010 at 9:31 AM, Jon Harrop wrote: > On Friday 19 February 2010 18:46:30 Tom Tobin wrote: >> On Fri, Feb 19, 2010 at 1:57 PM, Jon Harrop wrote: >> > GHCI seems to require type definitions to be described in a separate file >> > and then loaded into the REPL, which is seriously tedious. >> > >> > Are there any Haskell REPLs that don't have such limitations and, >> > preferably, use JIT compilation instead of an interpreter? >> >> I run Haskell in an inferior shell in Emacs alongside haskell-mode; >> it's easy to get immediate feedback to my changes that way. > > What's your procedure for getting ghci to interpret a type definition? I just hit C-c C-r in my Haskell source file's buffer to get it reloaded in the inferior ghci shell. I think it's best to think of the source file as your scratchpad for editing, with the "main" function changed as you go along to show relevant output for testing, and the inferior ghci buffer as just an "output window" of sorts. It's not the same as writing code directly shell, but I actually prefer it this way for all languages now, not just Haskell -- particularly since it's much nicer editing code in a proper editor vs. in a shell. From korpios at korpios.com Sat Feb 20 12:00:21 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 20 11:30:59 2010 Subject: [Haskell-beginners] Moment of enlightenment for lazy evaluation Message-ID: Instead of a question, I thought I'd share a moment of lazy-evaluation enlightenment I had last night. I have some code that recursively descends a directory, gets the SHA1 hashes for all the files, and builds a map of which file paths share the same SHA1 hash. The code that actually generates the hash looked like this: sha1file :: FilePath -> IO String sha1file fn = do bs <- expandPath fn >>= BSL.readFile return $ PureSHA.showDigest $ PureSHA.sha1 bs Everything worked fine on paths without many files in them, but choked on paths with many files: "Exception: getCurrentDirectory: resource exhausted (Too many open files)" This was driving me crazy; ByteString.Lazy.readFile is supposed to close the file once it's done. I kept going over my code, wondering what was at fault, until it finally clicked: *the hashes weren't being generated until I actually tried to view them*, and thus all the files were being held open until that point! I made a single change to my "sha1file" function: sha1file :: FilePath -> IO String sha1file fn = do bs <- expandPath fn >>= BSL.readFile return $ PureSHA.showDigest $! PureSHA.sha1 bs (the "$!") ... and everything worked perfectly. The code now finished processing each file before opening the next one, and I was happy. :-) From kane96 at gmx.de Sat Feb 20 13:18:57 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Sat Feb 20 12:49:42 2010 Subject: [Haskell-beginners] list of integers to list of nats In-Reply-To: <3690ee141002200419x20181101l4cb5b76c05ee9a0c@mail.gmail.com> References: <20100220113930.284290@gmx.net> <3690ee141002200419x20181101l4cb5b76c05ee9a0c@mail.gmail.com> Message-ID: <20100220181857.284320@gmx.net> the function should produce Nothing if there is a negative Int in the input list and otherwise Just with the list of the corresponding Nats mapM looks like the right function for that, so I tried some examples that work like I need it. But in case of my exercise: mapM toEnum [1,2,3,4] :: Nat doesn't work. -------- Original-Nachricht -------- > Datum: Sat, 20 Feb 2010 13:19:32 +0100 > Von: "Jonas Almstr?m Dureg?rd" > An: kane96@gmx.de > Betreff: Re: [Haskell-beginners] list of integers to list of nats > Homework? > > Should mapIntsToNats [-1] be Nothing? > > One way to to do this is to check if any integer in the list is > negative (for instance using the any function) and if so return > Nothing, otherwise Just map an Int-to-Nat function across the values > in the list (there is already such a function in your code). > > A slightly more elegant solution uses the fact that Maybe is a Monad, > so the function > > mapM :: Monad m => (a -> m b) -> [a] -> m [b] > > is also mapM :: (Int -> Maybe Nat) -> [Int] -> Maybe [Nat]. > > so mapIntsToNats = mapM f, for some function f :: Int -> Maybe Nat > > Hope this helps > /Jonas Dureg?rd > > > On 20 February 2010 12:39, wrote: > > Hi, > > I have to write a function which maps a list of integers to a list of > the corresponding nats. The following code is already there: > > > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > > > instance Enum Nat where > > ? ?toEnum i | i < 0 ? ? ? ?= error "Enum_Nat.toEnum: Negative > integer" > > ? ? ? ? ? ? | i == 0 ? ? ? = Z > > ? ? ? ? ? ? | otherwise ? ?= S (toEnum (i-1)) > > > > the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] > > so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))] > > > > how can I do that? > > > > > > > > -- > > NEU: Mit GMX DSL ?ber 1000,- ? sparen! > > http://portal.gmx.net/de/go/dsl02 > > _______________________________________________ > > Beginners mailing list > > Beginners@haskell.org > > http://www.haskell.org/mailman/listinfo/beginners > > -- NEU: Mit GMX DSL ?ber 1000,- ? sparen! http://portal.gmx.net/de/go/dsl02 From jon at ffconsultancy.com Sat Feb 20 14:44:30 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Sat Feb 20 12:59:10 2010 Subject: [Haskell-beginners] Decent Haskell REPL? In-Reply-To: References: <201002191957.50704.jon@ffconsultancy.com> <201002201531.31170.jon@ffconsultancy.com> Message-ID: <201002201944.30855.jon@ffconsultancy.com> On Saturday 20 February 2010 16:33:30 Tom Tobin wrote: > I just hit C-c C-r in my Haskell source file's buffer to get it > reloaded in the inferior ghci shell. > > I think it's best to think of the source file as your scratchpad for > editing, with the "main" function changed as you go along to show > relevant output for testing, and the inferior ghci buffer as just an > "output window" of sorts. It's not the same as writing code directly > shell, but I actually prefer it this way for all languages now, not > just Haskell -- particularly since it's much nicer editing code in a > proper editor vs. in a shell. I see. What happens if your program is producing non-trivial output that takes a long time to compute? How do you get around complete recomputation at the evaluation of every new expression? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From korpios at korpios.com Sat Feb 20 14:08:52 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 20 13:39:30 2010 Subject: [Haskell-beginners] Decent Haskell REPL? In-Reply-To: <201002201944.30855.jon@ffconsultancy.com> References: <201002191957.50704.jon@ffconsultancy.com> <201002201531.31170.jon@ffconsultancy.com> <201002201944.30855.jon@ffconsultancy.com> Message-ID: On Sat, Feb 20, 2010 at 1:44 PM, Jon Harrop wrote: > On Saturday 20 February 2010 16:33:30 Tom Tobin wrote: >> I just hit C-c C-r in my Haskell source file's buffer to get it >> reloaded in the inferior ghci shell. >> >> I think it's best to think of the source file as your scratchpad for >> editing, with the "main" function changed as you go along to show >> relevant output for testing, and the inferior ghci buffer as just an >> "output window" of sorts. ?It's not the same as writing code directly >> shell, but I actually prefer it this way for all languages now, not >> just Haskell -- particularly since it's much nicer editing code in a >> proper editor vs. in a shell. > > I see. What happens if your program is producing non-trivial output that takes > a long time to compute? How do you get around complete recomputation at the > evaluation of every new expression? Hm, I'm not sure. I do seem to lose any local "let" bindings I do in the ghci window when I reload, and the manual for ghci doesn't seem to offer any way to save values between reloads [1]. I know you can avoid that in other languages' shells (e.g., Python). One workaround I can think of is to use the "binary" package to save intermediate computations out to disk, but that seems somewhat cumbersome when you're trying to quickly prototype your code. [1] http://www.haskell.org/ghc/docs/latest/html/users_guide/interactive-evaluation.html From mutilating.cauliflowers.stephen at blacksapphire.com Sat Feb 20 17:42:37 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sat Feb 20 17:13:21 2010 Subject: [Haskell-beginners] Moment of enlightenment for lazy evaluation In-Reply-To: References: Message-ID: <4B80655D.8050707@blacksapphire.com> Tom, The bad news is that 1. Haskell makes no guarantee about when the files are closed, 2. file handles are a limited resource, and 3. lazy I/O doesn't handle errors in a recoverable fashion. Unfortunately this means that lazy I/O is fundamentally unsound. The only safe way to do it is to read the file strictly in blocks using Data.ByteString.hGet. Steve Tom Tobin wrote: > Instead of a question, I thought I'd share a moment of lazy-evaluation > enlightenment I had last night. > > I have some code that recursively descends a directory, gets the SHA1 > hashes for all the files, and builds a map of which file paths share > the same SHA1 hash. The code that actually generates the hash looked > like this: > > sha1file :: FilePath -> IO String > sha1file fn = do > bs <- expandPath fn >>= BSL.readFile > return $ PureSHA.showDigest $ PureSHA.sha1 bs > > Everything worked fine on paths without many files in them, but choked > on paths with many files: > > "Exception: getCurrentDirectory: resource exhausted (Too many open files)" > > This was driving me crazy; ByteString.Lazy.readFile is supposed to > close the file once it's done. I kept going over my code, wondering > what was at fault, until it finally clicked: *the hashes weren't being > generated until I actually tried to view them*, and thus all the files > were being held open until that point! I made a single change to my > "sha1file" function: > > sha1file :: FilePath -> IO String > sha1file fn = do > bs <- expandPath fn >>= BSL.readFile > return $ PureSHA.showDigest $! PureSHA.sha1 bs > > (the "$!") ... and everything worked perfectly. The code now finished > processing each file before opening the next one, and I was happy. > :-) > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From korpios at korpios.com Sat Feb 20 20:23:48 2010 From: korpios at korpios.com (Tom Tobin) Date: Sat Feb 20 19:54:26 2010 Subject: [Haskell-beginners] Moment of enlightenment for lazy evaluation In-Reply-To: <4B80655D.8050707@blacksapphire.com> References: <4B80655D.8050707@blacksapphire.com> Message-ID: On Sat, Feb 20, 2010 at 4:42 PM, Stephen Blackheath [to Haskell-Beginners] wrote: > Tom, > > The bad news is that 1. Haskell makes no guarantee about when the files > are closed, Hmm, Data.ByteString.Lazy.readFile's docstring says: "Read an entire file lazily into a ByteString. The Handle will be held open until EOF is encountered." It certainly seemed to change matters once I switched that $ to $!, though; I don't see why that would have helped me unless the handles were indeed being closed. > 2. file handles are a limited resource Well, yes, that's why I ran into the original problem. > and 3. lazy I/O > doesn't handle errors in a recoverable fashion. I suppose this will be something I'll run into before too long. > Unfortunately this > means that lazy I/O is fundamentally unsound. > > The only safe way to do it is to read the file strictly in blocks using > Data.ByteString.hGet. But with the strict version of ByteString, how would I compute the SHA1 hash of an 8 GB file on a machine with quite a bit less memory? I can't imagine Haskell just has no way to handle a case that other languages handle easily. From daniel.is.fischer at web.de Sat Feb 20 20:57:11 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Feb 20 20:29:45 2010 Subject: [Haskell-beginners] Moment of enlightenment for lazy evaluation In-Reply-To: References: <4B80655D.8050707@blacksapphire.com> Message-ID: <201002210257.12497.daniel.is.fischer@web.de> Am Sonntag 21 Februar 2010 02:23:48 schrieb Tom Tobin: > On Sat, Feb 20, 2010 at 4:42 PM, Stephen Blackheath [to > Haskell-Beginners] > > wrote: > > Tom, > > > > The bad news is that 1. Haskell makes no guarantee about when the > > files are closed, > > Hmm, Data.ByteString.Lazy.readFile's docstring says: > > "Read an entire file lazily into a ByteString. The Handle will be held > open until EOF is encountered." There is no hard guarantee when the file will be closed, but looking at the relevant code, hGetContentsN :: Int -> Handle -> IO ByteString hGetContentsN k h = lazyRead -- TODO close on exceptions where lazyRead = unsafeInterleaveIO loop loop = do c <- S.hGetNonBlocking h k --TODO: I think this should distinguish EOF from no data available -- the underlying POSIX call makes this distincion, returning either -- 0 or EAGAIN if S.null c then do eof <- hIsEOF h if eof then hClose h >> return Empty else hWaitForInput h (-1) >> loop else do cs <- lazyRead return (Chunk c cs) I'd say the file is closed as soon as EOF is encountered. If you don't open too many files before you've finished reading, it shouldn't be a problem. > > It certainly seemed to change matters once I switched that $ to $!, > though; I don't see why that would have helped me unless the handles > were indeed being closed. > Right. The $! forced the file to be read until the end, so it was closed before too many others were opened. > > 2. file handles are a limited resource > > Well, yes, that's why I ran into the original problem. > > > and 3. lazy I/O > > doesn't handle errors in a recoverable fashion. > > I suppose this will be something I'll run into before too long. > > > Unfortunately this > > means that lazy I/O is fundamentally unsound. > > > > The only safe way to do it is to read the file strictly in blocks > > using Data.ByteString.hGet. > > But with the strict version of ByteString, how would I compute the > SHA1 hash of an 8 GB file on a machine with quite a bit less memory? > I can't imagine Haskell just has no way to handle a case that other > languages handle easily. Incrementally, like the SHA1 hash is computed with a lazy ByteString. Read a chunk of the file (multiple of 512 bits is a good idea), process it, read next chunk, ..., until the end, then close the file. The difference is that you have exact control what happens when this way, the unsafeInterleaveIO in the lazy ByteString code takes that control away. However, by forcing the results at the proper places, you gain enough control to avoid the leaking of file handles and several other unpleasant surprises - normally, at least, there may be cases where you can't. From tgh at pdx.edu Sat Feb 20 22:07:50 2010 From: tgh at pdx.edu (Tyler Hayes) Date: Sat Feb 20 21:38:24 2010 Subject: [Haskell-beginners] help with error Message-ID: <1266721670.4036.10.camel@ubuntu.ubuntu-domain> I'm getting an error and I do not know why... This is what I have: class Finite a where elements' :: [a] instance (Finite a, Show a, Show b) => Show (a -> b) where show f = concat (map show [ a | a <- elements'::[a] ]) and this is what ghci gives me: Could not deduce (Finite a1) from the context () arising from a use of `elements'' at Hw06.lhs:119:42-50 Possible fix: add (Finite a1) to the context of an expression type signature In the expression: elements' :: [a] In a stmt of a list comprehension: a <- elements' :: [a] In the second argument of `map', namely `[a | a <- elements' :: [a]]' What's going on here? Thanks for the help! - Tyler From daniel.is.fischer at web.de Sat Feb 20 22:36:32 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Feb 20 22:09:05 2010 Subject: [Haskell-beginners] help with error In-Reply-To: <1266721670.4036.10.camel@ubuntu.ubuntu-domain> References: <1266721670.4036.10.camel@ubuntu.ubuntu-domain> Message-ID: <201002210436.33517.daniel.is.fischer@web.de> Am Sonntag 21 Februar 2010 04:07:50 schrieb Tyler Hayes: > I'm getting an error and I do not know why... > > This is what I have: > > > class Finite a where > elements' :: [a] > > instance (Finite a, Show a, Show b) => Show (a -> b) where > show f = concat (map show [ a | a <- elements'::[a] ]) > > > and this is what ghci gives me: > > > Could not deduce (Finite a1) from the context () > arising from a use of `elements'' at Hw06.lhs:119:42-50 > Possible fix: > add (Finite a1) to the context of an expression type signature > In the expression: elements' :: [a] > In a stmt of a list comprehension: a <- elements' :: [a] > In the second argument of `map', namely > `[a | a <- elements' :: [a]]' > > > What's going on here? All type variables are implicitly universally quantified. Thus the type variable a in [a | a <- elements' :: [a] ] is *not* the type variable a from the signature, it's a fresh type variable (and promises something you can't keep, that elements' belongs to *every* list type). In GHC, you can bring the type variables from the signature into scope by enabling ScopedTypeVariables and explicitly quantifying the type variables: {-# LANGUAGE ScopedTypeVariables #-} -- or -XScopedTypeVariables on the command line class Finite a where elements' :: [a] instance forall a b. (Finite a, Show a, Show b) => Show (a -> b) where show f = concatMap show (elements' :: [a]) But that isn't really a good show instance, it involves neither b nor f, perhaps you'd rather want instance (Finite a, Show a, Show b) => Show (a -> b) where show f = show [ (x, f x) | x <- elements' ] and then you don't need ScopedTypeVariables and explicit forall. > > Thanks for the help! > - Tyler From tgh at pdx.edu Sat Feb 20 23:04:46 2010 From: tgh at pdx.edu (Tyler Hayes) Date: Sat Feb 20 22:35:20 2010 Subject: [Haskell-beginners] help with error In-Reply-To: <201002210436.33517.daniel.is.fischer@web.de> References: <1266721670.4036.10.camel@ubuntu.ubuntu-domain> <201002210436.33517.daniel.is.fischer@web.de> Message-ID: <1266725086.4036.30.camel@ubuntu.ubuntu-domain> Thanks that helps a lot! - Tyler On Sun, 2010-02-21 at 04:36 +0100, Daniel Fischer wrote: > Am Sonntag 21 Februar 2010 04:07:50 schrieb Tyler Hayes: > > I'm getting an error and I do not know why... > > > > This is what I have: > > > > > > class Finite a where > > elements' :: [a] > > > > instance (Finite a, Show a, Show b) => Show (a -> b) where > > show f = concat (map show [ a | a <- elements'::[a] ]) > > > > > > and this is what ghci gives me: > > > > > > Could not deduce (Finite a1) from the context () > > arising from a use of `elements'' at Hw06.lhs:119:42-50 > > Possible fix: > > add (Finite a1) to the context of an expression type signature > > In the expression: elements' :: [a] > > In a stmt of a list comprehension: a <- elements' :: [a] > > In the second argument of `map', namely > > `[a | a <- elements' :: [a]]' > > > > > > What's going on here? > > All type variables are implicitly universally quantified. Thus the type > variable a in [a | a <- elements' :: [a] ] is *not* the type variable a > from the signature, it's a fresh type variable (and promises something you > can't keep, that elements' belongs to *every* list type). > > In GHC, you can bring the type variables from the signature into scope by > enabling ScopedTypeVariables and explicitly quantifying the type variables: > > {-# LANGUAGE ScopedTypeVariables #-} > -- or -XScopedTypeVariables on the command line > > class Finite a where > elements' :: [a] > > instance forall a b. (Finite a, Show a, Show b) => Show (a -> b) where > show f = concatMap show (elements' :: [a]) > > But that isn't really a good show instance, it involves neither b nor f, > perhaps you'd rather want > > instance (Finite a, Show a, Show b) => Show (a -> b) where > show f = show [ (x, f x) | x <- elements' ] > > and then you don't need ScopedTypeVariables and explicit forall. > > > > > Thanks for the help! > > - Tyler > > From stephen.tetley at gmail.com Sun Feb 21 07:31:59 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Feb 21 07:02:35 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> Message-ID: <5fdc56d71002210431v47ea654ai948770c14c31fd93@mail.gmail.com> Hello all How are search trees generated and what is their 'shape' - i.e. leaf labelled, node labelled, binary trees or rose trees? I've a functional reformulation of the Wikipedia algorithm which is about the same line count (excepting auxiliaries, which is a bit of a cheat), but its producing bad results on a leaf and node labelled rose tree. By the way, the imperative essence of the negascout algorithm and what makes it elegant is how it cuts off (control flow), rather than statefulness (assignment). Even though the line count is roughly the same and I believe I match the traversal behaviour / cut offs, the imperative version is simply nicer than my functional version. Best wishes Stephen From kane96 at gmx.de Sun Feb 21 09:57:09 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Feb 21 09:27:47 2010 Subject: [Haskell-beginners] list of integers to list of nats In-Reply-To: <20100220181857.284320@gmx.net> References: <20100220113930.284290@gmx.net> <3690ee141002200419x20181101l4cb5b76c05ee9a0c@mail.gmail.com> <20100220181857.284320@gmx.net> Message-ID: <20100221145709.120280@gmx.net> I tried: map toEnum [1,2,3,4]) :: [Nat] which works normally, but not for Maybe in: mapIntsToNats :: [Int] -> Maybe [Nat] -------- Original-Nachricht -------- > Datum: Sat, 20 Feb 2010 19:18:57 +0100 > Von: kane96@gmx.de > An: jonas.duregard@gmail.com > CC: beginners@haskell.org > Betreff: Re: [Haskell-beginners] list of integers to list of nats > the function should produce Nothing if there is a negative Int in the > input list and otherwise Just with the list of the corresponding Nats > > mapM looks like the right function for that, so I tried some examples that > work like I need it. But in case of my exercise: > > mapM toEnum [1,2,3,4] :: Nat > > doesn't work. > > > -------- Original-Nachricht -------- > > Datum: Sat, 20 Feb 2010 13:19:32 +0100 > > Von: "Jonas Almstr?m Dureg?rd" > > An: kane96@gmx.de > > Betreff: Re: [Haskell-beginners] list of integers to list of nats > > > Homework? > > > > Should mapIntsToNats [-1] be Nothing? > > > > One way to to do this is to check if any integer in the list is > > negative (for instance using the any function) and if so return > > Nothing, otherwise Just map an Int-to-Nat function across the values > > in the list (there is already such a function in your code). > > > > A slightly more elegant solution uses the fact that Maybe is a Monad, > > so the function > > > > mapM :: Monad m => (a -> m b) -> [a] -> m [b] > > > > is also mapM :: (Int -> Maybe Nat) -> [Int] -> Maybe [Nat]. > > > > so mapIntsToNats = mapM f, for some function f :: Int -> Maybe Nat > > > > Hope this helps > > /Jonas Dureg?rd > > > > > > On 20 February 2010 12:39, wrote: > > > Hi, > > > I have to write a function which maps a list of integers to a list of > > the corresponding nats. The following code is already there: > > > > > > data Nat = Z | S Nat deriving (Eq,Ord,Show) > > > > > > instance Enum Nat where > > > ? ?toEnum i | i < 0 ? ? ? ?= error "Enum_Nat.toEnum: Negative > > integer" > > > ? ? ? ? ? ? | i == 0 ? ? ? = Z > > > ? ? ? ? ? ? | otherwise ? ?= S (toEnum (i-1)) > > > > > > the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] > > > so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))] > > > > > > how can I do that? > > > > > > > > > > > > -- > > > NEU: Mit GMX DSL ?ber 1000,- ? sparen! > > > http://portal.gmx.net/de/go/dsl02 > > > _______________________________________________ > > > Beginners mailing list > > > Beginners@haskell.org > > > http://www.haskell.org/mailman/listinfo/beginners > > > > > -- > NEU: Mit GMX DSL ?ber 1000,- ? sparen! > http://portal.gmx.net/de/go/dsl02 > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From daniel.is.fischer at web.de Sun Feb 21 10:28:58 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Feb 21 10:01:30 2010 Subject: [Haskell-beginners] list of integers to list of nats In-Reply-To: <20100221145709.120280@gmx.net> References: <20100220113930.284290@gmx.net> <20100220181857.284320@gmx.net> <20100221145709.120280@gmx.net> Message-ID: <201002211628.58865.daniel.is.fischer@web.de> Am Sonntag 21 Februar 2010 15:57:09 schrieb kane96@gmx.de: > I tried: map toEnum [1,2,3,4]) :: [Nat] > which works normally, but not for Maybe in: mapIntsToNats :: [Int] -> > Maybe [Nat] > To use mapM, you need a function of type (f :: Int -> Maybe Nat). toEnum has type (Int -> Nat), so you can't use that directly. Think: when should f k be Nothing and what should f k be in the other cases? From kane96 at gmx.de Sun Feb 21 11:28:41 2010 From: kane96 at gmx.de (kane96@gmx.de) Date: Sun Feb 21 10:59:17 2010 Subject: [Haskell-beginners] list of integers to list of nats In-Reply-To: <201002211628.58865.daniel.is.fischer@web.de> References: <20100220113930.284290@gmx.net> <20100220181857.284320@gmx.net> <20100221145709.120280@gmx.net> <201002211628.58865.daniel.is.fischer@web.de> Message-ID: <20100221162841.120300@gmx.net> f should be Nothing if k is negative and otherwise k should be toEnum k...?! -------- Original-Nachricht -------- > Datum: Sun, 21 Feb 2010 16:28:58 +0100 > Von: Daniel Fischer > An: beginners@haskell.org > CC: kane96@gmx.de > Betreff: Re: [Haskell-beginners] list of integers to list of nats > Am Sonntag 21 Februar 2010 15:57:09 schrieb kane96@gmx.de: > > I tried: map toEnum [1,2,3,4]) :: [Nat] > > which works normally, but not for Maybe in: mapIntsToNats :: [Int] -> > > Maybe [Nat] > > > > To use mapM, you need a function of type (f :: Int -> Maybe Nat). toEnum > has type (Int -> Nat), so you can't use that directly. > Think: when should f k be Nothing and what should f k be in the other > cases? -- Sicherer, schneller und einfacher. Die aktuellen Internet-Browser - jetzt kostenlos herunterladen! http://portal.gmx.net/de/go/atbrowser From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 21 14:10:37 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 21 13:41:29 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <5fdc56d71002210431v47ea654ai948770c14c31fd93@mail.gmail.com> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> <5fdc56d71002210431v47ea654ai948770c14c31fd93@mail.gmail.com> Message-ID: <4B81852D.3080106@blacksapphire.com> Stephen, Mikhail & all, I'll have a go... Wikipedia's imperative pseudo-code: function negascout(node, depth, ?, ?) if node is a terminal node or depth = 0 return the heuristic value of node b := ? (* initial window is (-?, -?) *) foreach child of node a := -negascout (child, depth-1, -b, -?) if a>? ? := a if ??? return ? (* Beta cut-off *) if ??b (* check if null-window failed high*) ? := -negascout(child, depth-1, -?, -?) (* full re-search *) if ??? return ? (* Beta cut-off *) b := ?+1 (* set new null window *) return ? My attempt to render into Haskell without ST monad and without attempting to understand the algorithm at all. Version 1 with lets negascout :: Node -> Int -> Int -> Int -> Int negascout node depth _ _ | terminal node || depth == 0 = heuristic node negascout node depth alpha beta = ns (children node) alpha beta beta -- initial window is (-beta, -alpha) where ns (ch:chs) alpha beta b = let alpha' = alpha `max` negascout ch (depth-1) (-b) (-alpha) in if alpha' >= beta then alpha' else -- beta cut-off if alpha' >= b then -- full re-search let alpha'' = -negascout ch (depth-1) (-beta) (-alpha) in if alpha'' >= beta then alpha'' -- beta cut-off else ns chs alpha'' beta (alpha''+1) -- new window else ns chs alpha' beta (alpha'+1) -- new window ns [] alpha _ _ = alpha Version 2 with cases negascout :: Node -> Int -> Int -> Int -> Int negascout node depth _ _ | terminal node || depth == 0 = heuristic node negascout node depth alpha beta = ns (children node) alpha beta -- initial window is (-beta, -alpha) where ns (ch:chs) alpha b = case alpha `max` negascout ch (depth-1) (-b) (-alpha) of alpha' | alpha' >= beta -> alpha' -- beta cut-off alpha' | alpha' >= b -> -- full re-search case -negascout ch (depth-1) (-beta) (-alpha) of alpha'' | alpha'' >= beta -> alpha'' -- beta cut-off alpha'' -> ns chs alpha'' (alpha''+1) -- new window alpha' -> ns chs alpha' (alpha'+1) -- new window ns [] alpha _ = alpha I think with case, it's slightly more readable. Marginally more verbose than the imperative version, because Haskell makes you do your state keeping more explicitly. Personally I find the Haskell easier to read. When I read the imperative version, it takes work to assemble in my head what is written out explicitly in the Haskell, but maybe that's just me. I certainly don't think the Haskell version is any more complex. I think there are cases where mutability is so important to an algorithm that Haskell struggles (at least in terms of performance), but I don't think this is one of those cases. Just for fun here's another version where I'm breaking it up into three parts: data Next a = Cont a | Break a breakableFoldl :: (a -> b -> Next a) -> a -> [b] -> a breakableFoldl body state xs = loop state xs where loop state [] = state loop state (x:xs) = case body state x of Cont state' -> loop state' xs Break state' -> state' negascout :: Node -> Int -> Int -> Int -> Int negascout node depth _ _ | terminal node || depth == 0 = heuristic node negascout node depth alpha0 beta = alphaOut where (alphaOut, _) = breakableFoldl (\(alpha, b) ch -> (alpha `max` negascout ch (depth-1) (-b) (-alpha)) `betaCutoffOr` \alpha' -> if alpha' >= b then -- full re-search (-negascout ch (depth-1) (-beta) (-alpha)) `betaCutoffOr` \alpha'' -> Cont (alpha'', alpha''+1) else Cont (alpha', alpha'+1) ) (alpha0, beta) (children node) -- initial window is (-beta, -alpha) -- Break out if the input alpha value hits the beta cutoff, otherwise pass -- it to a non-cutoff case. betaCutoffOr :: Int -> (Int -> Next (Int,Int)) -> Next (Int,Int) betaCutoffOr alpha _ | alpha >= beta = Break (alpha, undefined) betaCutoffOr alpha nonCutoffCase = nonCutoffCase alpha This is a higher level of abstraction, which communicates intent fairly clearly, and shows how easily you can abstract common patterns out in Haskell. An improvement in this case? I think so, but there are arguments against that. Here's the missing code that makes each version above typecheck: data Node = Node { heuristic :: Int, children :: [Node] } terminal :: Node -> Bool terminal = undefined Steve Stephen Tetley wrote: > Hello all > > How are search trees generated and what is their 'shape' - i.e. leaf > labelled, node labelled, binary trees or rose trees? > > I've a functional reformulation of the Wikipedia algorithm which is > about the same line count (excepting auxiliaries, which is a bit of a > cheat), but its producing bad results on a leaf and node labelled rose > tree. > > By the way, the imperative essence of the negascout algorithm and what > makes it elegant is how it cuts off (control flow), rather than > statefulness (assignment). Even though the line count is roughly the > same and I believe I match the traversal behaviour / cut offs, the > imperative version is simply nicer than my functional version. > > Best wishes > > Stephen > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From mutilating.cauliflowers.stephen at blacksapphire.com Sun Feb 21 14:29:13 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Sun Feb 21 13:59:57 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <4B81852D.3080106@blacksapphire.com> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> <5fdc56d71002210431v47ea654ai948770c14c31fd93@mail.gmail.com> <4B81852D.3080106@blacksapphire.com> Message-ID: <4B818989.6020006@blacksapphire.com> All, And... A slight variation that shadows alpha (which some people don't like, but I think it's a great technique) and thereby avoids the mistake I made in my previous three versions where I forgot a ' in -negascout ch (depth-1) (-beta) (-alpha'). (You have to watch that in Haskell.) data Next a = Cont a | Break a breakableFoldl :: (a -> b -> Next a) -> a -> [b] -> a breakableFoldl body state xs = loop state xs where loop state [] = state loop state (x:xs) = case body state x of Cont state' -> loop state' xs Break state' -> state' negascout :: Node -> Int -> Int -> Int -> Int negascout node depth _ _ | terminal node || depth == 0 = heuristic node negascout node depth alpha0 beta = alphaOut where (alphaOut, _) = breakableFoldl (\(alpha, b) ch -> (alpha `max` negascout ch (depth-1) (-b) (-alpha)) `betaCutoffOr` \alpha -> if alpha >= b then -- full re-search (-negascout ch (depth-1) (-beta) (-alpha)) `betaCutoffOr` \alpha -> Cont (alpha, alpha+1) else Cont (alpha, alpha+1) ) (alpha0, beta) (children node) -- initial window is (-beta, -alpha) -- Break out if the input alpha value hits the beta cutoff, otherwise pass -- it to a non-cutoff case. betaCutoffOr :: Int -> (Int -> Next (Int,Int)) -> Next (Int,Int) betaCutoffOr alpha _ | alpha >= beta = Break (alpha, undefined) betaCutoffOr alpha nonCutoffCase = nonCutoffCase alpha Steve Stephen Blackheath [to Haskell-Beginners] wrote: > Stephen, Mikhail & all, > > I'll have a go... > > Wikipedia's imperative pseudo-code: > > function negascout(node, depth, ?, ?) > if node is a terminal node or depth = 0 > return the heuristic value of node > b := ? (* initial window is > (-?, -?) *) > foreach child of node > a := -negascout (child, depth-1, -b, -?) > if a>? > ? := a > if ??? > return ? (* Beta cut-off *) > if ??b (* check if > null-window failed high*) > ? := -negascout(child, depth-1, -?, -?) (* full re-search *) > if ??? > return ? (* Beta cut-off *) > b := ?+1 (* set new null > window *) > return ? > > My attempt to render into Haskell without ST monad and without > attempting to understand the algorithm at all. > > Version 1 with lets > > negascout :: Node -> Int -> Int -> Int -> Int > negascout node depth _ _ | terminal node || depth == 0 = heuristic node > negascout node depth alpha beta = > ns (children node) alpha beta beta -- initial window is (-beta, > -alpha) > where > ns (ch:chs) alpha beta b = > let alpha' = alpha `max` negascout ch (depth-1) (-b) (-alpha) > in if alpha' >= beta then alpha' else -- beta > cut-off > if alpha' >= b then -- full > re-search > let alpha'' = -negascout ch (depth-1) (-beta) (-alpha) > in if alpha'' >= beta then alpha'' -- beta cut-off > else ns chs alpha'' beta (alpha''+1) -- new window > else ns chs alpha' beta (alpha'+1) -- new window > ns [] alpha _ _ = alpha > > Version 2 with cases > > negascout :: Node -> Int -> Int -> Int -> Int > negascout node depth _ _ | terminal node || depth == 0 = heuristic node > negascout node depth alpha beta = > ns (children node) alpha beta -- initial window is (-beta, -alpha) > where > ns (ch:chs) alpha b = > case alpha `max` negascout ch (depth-1) (-b) (-alpha) of > alpha' | alpha' >= beta -> alpha' -- beta > cut-off > alpha' | alpha' >= b -> -- full > re-search > case -negascout ch (depth-1) (-beta) (-alpha) of > alpha'' | alpha'' >= beta -> alpha'' -- beta > cut-off > alpha'' -> ns chs alpha'' (alpha''+1) -- new window > alpha' -> ns chs alpha' (alpha'+1) -- new window > ns [] alpha _ = alpha > > I think with case, it's slightly more readable. Marginally more verbose > than the imperative version, because Haskell makes you do your state > keeping more explicitly. Personally I find the Haskell easier to read. > When I read the imperative version, it takes work to assemble in my > head what is written out explicitly in the Haskell, but maybe that's > just me. > > I certainly don't think the Haskell version is any more complex. I > think there are cases where mutability is so important to an algorithm > that Haskell struggles (at least in terms of performance), but I don't > think this is one of those cases. > > Just for fun here's another version where I'm breaking it up into three > parts: > > > data Next a = Cont a | Break a > > breakableFoldl :: (a -> b -> Next a) -> a -> [b] -> a > breakableFoldl body state xs = loop state xs > where > loop state [] = state > loop state (x:xs) = case body state x of > Cont state' -> loop state' xs > Break state' -> state' > > negascout :: Node -> Int -> Int -> Int -> Int > negascout node depth _ _ | terminal node || depth == 0 = heuristic node > negascout node depth alpha0 beta = alphaOut > where > (alphaOut, _) = breakableFoldl (\(alpha, b) ch -> > (alpha `max` negascout ch (depth-1) (-b) (-alpha)) > `betaCutoffOr` \alpha' -> > if alpha' >= b then -- full re-search > (-negascout ch (depth-1) (-beta) (-alpha)) > `betaCutoffOr` \alpha'' -> Cont (alpha'', > alpha''+1) > else > Cont (alpha', alpha'+1) > ) (alpha0, beta) (children node) -- initial window is > (-beta, -alpha) > > -- Break out if the input alpha value hits the beta cutoff, > otherwise pass > -- it to a non-cutoff case. > betaCutoffOr :: Int -> (Int -> Next (Int,Int)) -> Next (Int,Int) > betaCutoffOr alpha _ | alpha >= beta = Break (alpha, undefined) > betaCutoffOr alpha nonCutoffCase = nonCutoffCase alpha > > > This is a higher level of abstraction, which communicates intent fairly > clearly, and shows how easily you can abstract common patterns out in > Haskell. An improvement in this case? I think so, but there are > arguments against that. > > Here's the missing code that makes each version above typecheck: > > data Node = Node { > heuristic :: Int, > children :: [Node] > } > > terminal :: Node -> Bool > terminal = undefined > > > Steve > > Stephen Tetley wrote: >> Hello all >> >> How are search trees generated and what is their 'shape' - i.e. leaf >> labelled, node labelled, binary trees or rose trees? >> >> I've a functional reformulation of the Wikipedia algorithm which is >> about the same line count (excepting auxiliaries, which is a bit of a >> cheat), but its producing bad results on a leaf and node labelled rose >> tree. >> >> By the way, the imperative essence of the negascout algorithm and what >> makes it elegant is how it cuts off (control flow), rather than >> statefulness (assignment). Even though the line count is roughly the >> same and I believe I match the traversal behaviour / cut offs, the >> imperative version is simply nicer than my functional version. >> >> Best wishes >> >> Stephen >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners >> > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From stephen.tetley at gmail.com Sun Feb 21 15:07:29 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Sun Feb 21 14:38:03 2010 Subject: [Haskell-beginners] Translating imperative algorithms to Haskell In-Reply-To: <4B818989.6020006@blacksapphire.com> References: <4B7EEF77.3010004@gmail.com> <20100219211859.GA5386@kira.casa> <4B7F0C73.50506@gmail.com> <5fdc56d71002191506n4f00383q75d9d99dea06a098@mail.gmail.com> <5fdc56d71002210431v47ea654ai948770c14c31fd93@mail.gmail.com> <4B81852D.3080106@blacksapphire.com> <4B818989.6020006@blacksapphire.com> Message-ID: <5fdc56d71002211207j4e03b8a8ma9d7cddc1c1886c6@mail.gmail.com> Hi Stephen I'd be tempted to make the 'fold' problem specific (especially as I'm not sure I'd call a fold a 'fold' if it breaks early). Here's what I came up with though it seems to have a bug somewhere. The Step and Window types might benefit strictness annos in real life. The imperative version on Wikipedia is far clearer than either mine or yours though. Best wishes Stephen data Tree a = Node a [Tree a] | Leaf a deriving (Eq,Show) data Step a = NewWindow a a | BetaCutoff a data Window a = Win a a runCutoff :: [(Window a -> Step a)] -> Window a -> a runCutoff [] (Win alp _) = alp runCutoff (f:fs) ab = case f ab of NewWindow a b -> runCutoff fs (Win a b) BetaCutoff a -> a cutoff :: a -> (a -> Bool) -> (a -> Step a) -> Step a cutoff a test elsek | test a = BetaCutoff a | otherwise = elsek a negascout :: Tree Int -> Int -> (Window Int) -> Int negascout (Leaf h) _ _ = h negascout (Node h _ ) d _ | d <= 0 = h negascout (Node _ ns) d w@(Win _ b0) = runCutoff (map scout ns) w where scout _ (Win a _) | a >= b0 = BetaCutoff a scout node (Win a b) = let a' = max a (nega node (-b) (-a)) in cutoff a' (>= b0) (\x -> full node (Win x b)) full node (Win a b) = let a' = nega node (-b0) (-a) in cutoff a' (>= b) (\x -> NewWindow x (x+1)) nega node x y = negate $ negascout node (d-1) (Win x y) On 21 February 2010 19:29, Stephen Blackheath [to Haskell-Beginners] wrote: > All, > > And... A slight variation that shadows alpha (which some people don't > like, but I think it's a great technique) and thereby avoids the mistake > I made in my previous three versions where I forgot a ' in -negascout ch > (depth-1) (-beta) (-alpha'). ?(You have to watch that in Haskell.) > From Christian.Maeder at dfki.de Mon Feb 22 05:25:19 2010 From: Christian.Maeder at dfki.de (Christian Maeder) Date: Mon Feb 22 04:55:53 2010 Subject: [Haskell-beginners] Re: list of integers to list of nats In-Reply-To: <20100220181857.284320@gmx.net> References: <20100220113930.284290@gmx.net> <3690ee141002200419x20181101l4cb5b76c05ee9a0c@mail.gmail.com> <20100220181857.284320@gmx.net> Message-ID: <4B825B8F.6010901@dfki.de> kane96@gmx.de schrieb: > the function should produce Nothing if there is a negative Int in the input list and otherwise Just with the list of the corresponding Nats > > mapM looks like the right function for that, so I tried some examples that work like I need it. But in case of my exercise: > > mapM toEnum [1,2,3,4] :: Nat > > doesn't work. Surely, it does not work, because the type of your first argument "toEnum" does not match the expected type "Int -> Maybe Nat", as pointed out below. Furthermore the overall result type is not "Nat" nor "[Nat]", but "Maybe [Nat]". Did you have higher order functions (like mapM or map) in your course? If not, you are supposed to program "mapIntsToNats" using explizit recursion over lists (and using case-distinctions aka pattern matching for Lists and the Maybe data type). Cheers Christian P.S. If you're looking for a ready solution, you're (most likely) wrong here. We only try to help you, to find a solution yourself. >> mapM :: Monad m => (a -> m b) -> [a] -> m [b] >> >> is also mapM :: (Int -> Maybe Nat) -> [Int] -> Maybe [Nat]. >> >> so mapIntsToNats = mapM f, for some function f :: Int -> Maybe Nat You should be able to program such a function "f" (using "toEnum" or programming it from scratch similar to "toEnum"). From jeedward at yahoo.com Mon Feb 22 06:40:40 2010 From: jeedward at yahoo.com (John Edward) Date: Mon Feb 22 06:11:12 2010 Subject: [Haskell-beginners] Call for papers: MULTICONF-10, Orlando, USA, July 2010 Message-ID: <534074.14452.qm@web45911.mail.sp1.yahoo.com> It would be highly appreciated if you could share this announcement with your colleagues, students and individuals whose research is in computer science, computer engineering, information science and related areas. Call for papers: MULTICONF-10, Orlando, USA, July 2010 The 2010 multi-conference (MULTICONF-10) (website: http://www.PromoteResearch.org ) will be held during July 12-14, 2010 in Orlando, Florida, USA. The primary goal of MULTICONF is to promote research and developmental activities in computer science, information technology, control engineering, and related fields. Another goal is to promote the dissemination of research to a multidisciplinary audience and to facilitate communication among researchers, developers, practitioners in different fields. The following conferences are planned to be organized as part of MULTICONF-10. ? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-10) ? International Conference on Automation, Robotics and Control Systems (ARCS-10) ? International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-10) ? International Conference on Computer Communications and Networks (CCN-10) ? International Conference on Enterprise Information Systems and Web Technologies (EISWT-10) ? International Conference on High Performance Computing Systems (HPCS-10) ? International Conference on Information Security and Privacy (ISP-10) ? International Conference on Image and Video Processing and Computer Vision (IVPCV-10) ? International Conference on Software Engineering Theory and Practice (SETP-10) ? International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-10) MULTICONF-10 will be held at Imperial Swan Hotel and Suites. It is a full-service resort that puts you in the middle of the fun! Located 1/2 block south of the famed International Drive, the hotel is just minutes from great entertainment like Walt Disney World? Resort, Universal Studios and Sea World Orlando. Guests can enjoy free scheduled transportation to these theme parks, as well as spacious accommodations, outdoor pools and on-site dining ? all situated on 10 tropically landscaped acres. Here, guests can experience a full-service resort with discount hotel pricing in Orlando. Please see the website http://www.PromoteResearch.org for more details. Sincerely John Edward -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100222/393adabf/attachment-0001.html From iusty at k1024.org Mon Feb 22 17:02:13 2010 From: iusty at k1024.org (Iustin Pop) Date: Mon Feb 22 16:32:46 2010 Subject: [Haskell-beginners] GHC 6.12, -fwarn-unused-do-bind and Text.Printf Message-ID: <20100222220213.GA10887@teal.hq.k1024.org> Hi there, I'm trying to upgrade some code to ghc 6.12 but under -Wall, the new warning about unused do binds is triggering on Text.Printf.printf usage. This code: import Text.Printf main :: IO () main = do printf "Hello, world\n" printf "Hello the second time\n" When run with runhaskell -Wall gives: Warning: A do-notation statement discarded a result of type GHC.Prim.Any. Suppress this warning by saying "_ <- printf "Hello, world\n"", or by using the flag -fno-warn-unused-do-bind. Now, I'm confused why such a simple usage of printf triggers this warning; enforcing the first printf to type IO () fixes the warning, but it seems strange to no longer be able to simply write printf. Anyone knows a workaround, or can enlighten me what I'm doing wrong? A side question would be why we have "instance PrintfType (IO a)" instead of "instance PrintfType (IO ())"; what use is there for that generic type? Can printf return anything else than IO () (when used under IO at all)? thanks, iustin From daniel.is.fischer at web.de Mon Feb 22 17:47:09 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Feb 22 17:19:38 2010 Subject: [Haskell-beginners] GHC 6.12, -fwarn-unused-do-bind and Text.Printf In-Reply-To: <20100222220213.GA10887@teal.hq.k1024.org> References: <20100222220213.GA10887@teal.hq.k1024.org> Message-ID: <201002222347.09824.daniel.is.fischer@web.de> Am Montag 22 Februar 2010 23:02:13 schrieb Iustin Pop: > Hi there, > > I'm trying to upgrade some code to ghc 6.12 but under -Wall, the new > warning about unused do binds is triggering on Text.Printf.printf usage. > > This code: > > import Text.Printf > > main :: IO () > main = do > printf "Hello, world\n" > printf "Hello the second time\n" > > When run with runhaskell -Wall gives: > > Warning: A do-notation statement discarded a result of type > GHC.Prim.Any. Suppress this warning by saying "_ <- printf "Hello, > world\n"", or by using the flag -fno-warn-unused-do-bind. > > Now, I'm confused why such a simple usage of printf triggers this > warning; Because you don't bind the result of the first printf, which could be any type, so potentially interesting. The compiler doesn't know that 'printf fmt args' only ever returns undefined. > enforcing the first printf to type IO () fixes the warning, Yep, the compiler knows that a return value of type () is uninteresting enough to be discarded without warning. > but it seems strange to no longer be able to simply write printf. > > Anyone knows a workaround, or can enlighten me what I'm doing wrong? a) one of the options the compiler offered b) expression type signature c) use (>>) to explicitly tell the compiler "I want to discard the return value" I'd probably use -fno-warn-unused-do-bind (as an OPTIONS_GHC pragma in the relevant files). > > A side question would be why we have "instance PrintfType (IO a)" > instead of "instance PrintfType (IO ())"; Very good question. > what use is there for that > generic type? Can printf return anything else than IO () (when used > under IO at all)? > > thanks, > iustin From nicolas.pouillard at gmail.com Tue Feb 23 01:37:59 2010 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Tue Feb 23 01:08:31 2010 Subject: [Haskell-beginners] GHC 6.12, -fwarn-unused-do-bind and Text.Printf In-Reply-To: <20100222220213.GA10887@teal.hq.k1024.org> References: <20100222220213.GA10887@teal.hq.k1024.org> Message-ID: <4b8377c7.1c07d00a.3ed7.6ecc@mx.google.com> On Mon, 22 Feb 2010 23:02:13 +0100, Iustin Pop wrote: > Hi there, > > I'm trying to upgrade some code to ghc 6.12 but under -Wall, the new > warning about unused do binds is triggering on Text.Printf.printf usage. > > This code: > > import Text.Printf > > main :: IO () > main = do > printf "Hello, world\n" > printf "Hello the second time\n" > > When run with runhaskell -Wall gives: > > Warning: A do-notation statement discarded a result of type > GHC.Prim.Any. Suppress this warning by saying "_ <- printf "Hello, > world\n"", or by using the flag -fno-warn-unused-do-bind. > > Now, I'm confused why such a simple usage of printf triggers this > warning; enforcing the first printf to type IO () fixes the warning, but > it seems strange to no longer be able to simply write printf. > > Anyone knows a workaround, or can enlighten me what I'm doing wrong? What about providing a printf_ function with "IO ()" as return type? (like mapM vs mapM_) -- Nicolas Pouillard http://nicolaspouillard.fr From vandijk.roel at gmail.com Tue Feb 23 05:22:24 2010 From: vandijk.roel at gmail.com (Roel van Dijk) Date: Tue Feb 23 04:52:53 2010 Subject: [Haskell-beginners] GHC 6.12, -fwarn-unused-do-bind and Text.Printf In-Reply-To: <20100222220213.GA10887@teal.hq.k1024.org> References: <20100222220213.GA10887@teal.hq.k1024.org> Message-ID: On Mon, Feb 22, 2010 at 11:02 PM, Iustin Pop wrote: > A side question would be why we have "instance PrintfType (IO a)" > instead of "instance PrintfType (IO ())"; what use is there for that > generic type? Can printf return anything else than IO () (when used > under IO at all)? I can only guess, but perhaps because "instance PrintfType (IO ())" would require the FlexibleInstances language extension. I believe the current implementation of printf is fully Haskell98. From chimpionspeak at gmail.com Tue Feb 23 13:35:58 2010 From: chimpionspeak at gmail.com (Chimpion Chimpion) Date: Tue Feb 23 13:06:37 2010 Subject: [Haskell-beginners] Problem with GHCI. Message-ID: Could anyone tell me why this might be happening? I was trying to add some modules to the GHCi(:d +...). Couldn't match expected type `String -> IO String' against inferred type `()' In the expression: () In the expression: () :: String -> IO String In the definition of `__cmCompileExpr': __cmCompileExpr = () :: String -> IO String Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100223/f2aa0003/attachment.html From chimpionspeak at gmail.com Tue Feb 23 13:39:02 2010 From: chimpionspeak at gmail.com (Chimpion Chimpion) Date: Tue Feb 23 13:09:30 2010 Subject: [Haskell-beginners] Re: Problem with GHCI. In-Reply-To: References: Message-ID: Prelude> :d +Monad :1:22: Couldn't match expected type `String -> IO String' against inferred type `()' In the expression: () In the expression: () :: String -> IO String In the definition of `__cmCompileExpr': __cmCompileExpr = () :: String -> IO String That is the actual thing. On 24 February 2010 00:05, Chimpion Chimpion wrote: > Could anyone tell me why this might be happening? I was trying to add some > modules to the GHCi(:d +...). > > Couldn't match expected type `String -> IO String' > against inferred type `()' > In the expression: () > In the expression: () :: String -> IO String > In the definition of `__cmCompileExpr': > __cmCompileExpr = () :: String -> IO String > > Thank you. > > > -- What we've got here is a failure to communicate. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100223/9581fa50/attachment.html From mihai.maruseac at gmail.com Tue Feb 23 13:42:07 2010 From: mihai.maruseac at gmail.com (Mihai Maruseac) Date: Tue Feb 23 13:12:54 2010 Subject: [Haskell-beginners] Re: Problem with GHCI. In-Reply-To: References: Message-ID: On Tue, Feb 23, 2010 at 8:39 PM, Chimpion Chimpion wrote: > Prelude> :d +Monad > > :1:22: > ??? Couldn't match expected type `String -> IO String' > ?????????? against inferred type `()' > ??? In the expression: () > ??? In the expression: () :: String -> IO String > ??? In the definition of `__cmCompileExpr': > ??????? __cmCompileExpr = () :: String -> IO String > > That is the actual thing. > > On 24 February 2010 00:05, Chimpion Chimpion > wrote: >> >> Could anyone tell me why this might be happening? I was trying to add some >> modules to the GHCi(:d +...). >> >> ??? Couldn't match expected type `String -> IO String' >> ?????????? against inferred type `()' >> ??? In the expression: () >> ??? In the expression: () :: String -> IO String >> ??? In the definition of `__cmCompileExpr': >> ??????? __cmCompileExpr = () :: String -> IO String >> >> Thank you. Try :m +Control.Monad (if it is the same) From jrm8005 at gmail.com Tue Feb 23 13:42:44 2010 From: jrm8005 at gmail.com (Jorden Mauro) Date: Tue Feb 23 13:13:13 2010 Subject: [Haskell-beginners] Re: Problem with GHCI. In-Reply-To: References: Message-ID: <3aaafc131002231042r5e6d2b79w9c14f56e0cba7e4f@mail.gmail.com> On Tue, Feb 23, 2010 at 1:39 PM, Chimpion Chimpion wrote: > Prelude> :d +Monad > > :1:22: > ??? Couldn't match expected type `String -> IO String' > ?????????? against inferred type `()' > ??? In the expression: () > ??? In the expression: () :: String -> IO String > ??? In the definition of `__cmCompileExpr': > ??????? __cmCompileExpr = () :: String -> IO String > > That is the actual thing. > > On 24 February 2010 00:05, Chimpion Chimpion > wrote: >> >> Could anyone tell me why this might be happening? I was trying to add some >> modules to the GHCi(:d +...). >> >> ??? Couldn't match expected type `String -> IO String' >> ?????????? against inferred type `()' >> ??? In the expression: () >> ??? In the expression: () :: String -> IO String >> ??? In the definition of `__cmCompileExpr': >> ??????? __cmCompileExpr = () :: String -> IO String >> >> Thank you. :m +Monad :d is for something else. From chimpionspeak at gmail.com Tue Feb 23 14:18:24 2010 From: chimpionspeak at gmail.com (Chimpion Chimpion) Date: Tue Feb 23 13:48:52 2010 Subject: [Haskell-beginners] Re: Problem with GHCI. In-Reply-To: <3aaafc131002231042r5e6d2b79w9c14f56e0cba7e4f@mail.gmail.com> References: <3aaafc131002231042r5e6d2b79w9c14f56e0cba7e4f@mail.gmail.com> Message-ID: Oh alright. I was doing the wrong thing. Sorry for the bother. Thank you. On 24 February 2010 00:12, Jorden Mauro wrote: > On Tue, Feb 23, 2010 at 1:39 PM, Chimpion Chimpion > wrote: > > Prelude> :d +Monad > > > > :1:22: > > Couldn't match expected type `String -> IO String' > > against inferred type `()' > > In the expression: () > > In the expression: () :: String -> IO String > > In the definition of `__cmCompileExpr': > > __cmCompileExpr = () :: String -> IO String > > > > That is the actual thing. > > > > On 24 February 2010 00:05, Chimpion Chimpion > > wrote: > >> > >> Could anyone tell me why this might be happening? I was trying to add > some > >> modules to the GHCi(:d +...). > >> > >> Couldn't match expected type `String -> IO String' > >> against inferred type `()' > >> In the expression: () > >> In the expression: () :: String -> IO String > >> In the definition of `__cmCompileExpr': > >> __cmCompileExpr = () :: String -> IO String > >> > >> Thank you. > > :m +Monad > > :d is for something else. > -- What we've got here is a failure to communicate. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100223/a0fa1533/attachment-0001.html From jon at ffconsultancy.com Wed Feb 24 15:41:01 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed Feb 24 13:55:27 2010 Subject: [Haskell-beginners] Y-combinator Message-ID: <201002242041.01157.jon@ffconsultancy.com> OCaml can do this: $ ocaml -rectypes Objective Caml version 3.11.1 # let fix f = (fun x -> f(x x)) (fun x y -> f(x x) y);; val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = # fix (fun f -> function 0 -> 1 | n -> n*f(n-1)) 10;; - : int = 3628800 Haskell 98 doesn't seem to be able to type check that definition of the y-combinator directly. Is there a Haskell extension that would let it handle this? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From edgar at ymonad.com Wed Feb 24 15:30:19 2010 From: edgar at ymonad.com (edgar@ymonad.com) Date: Wed Feb 24 15:02:37 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <201002242041.01157.jon@ffconsultancy.com> References: <201002242041.01157.jon@ffconsultancy.com> Message-ID: <20100224203019.GA5234@ymonad.members.linode.com> http://lmgtfy.com/?q=y+combinator+haskell Cheers, Edgar On Wed, 24/Feb/2010 at 20:41 +0000, Jon Harrop wrote: > > OCaml can do this: > > $ ocaml -rectypes > Objective Caml version 3.11.1 > > # let fix f = (fun x -> f(x x)) (fun x y -> f(x x) y);; > val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = > > # fix (fun f -> function 0 -> 1 | n -> n*f(n-1)) 10;; > - : int = 3628800 > > Haskell 98 doesn't seem to be able to type check that definition of the > y-combinator directly. Is there a Haskell extension that would let it handle > this? > > -- > Dr Jon Harrop, Flying Frog Consultancy Ltd. > http://www.ffconsultancy.com/?e > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From ezyang at MIT.EDU Wed Feb 24 15:53:14 2010 From: ezyang at MIT.EDU (Edward Z. Yang) Date: Wed Feb 24 15:23:40 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <201002242041.01157.jon@ffconsultancy.com> References: <201002242041.01157.jon@ffconsultancy.com> Message-ID: <1267044766-sup-1137@ezyang> Excerpts from Jon Harrop's message of Wed Feb 24 15:41:01 -0500 2010: > OCaml can do this: > > $ ocaml -rectypes > Objective Caml version 3.11.1 > > # let fix f = (fun x -> f(x x)) (fun x y -> f(x x) y);; > val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = > > # fix (fun f -> function 0 -> 1 | n -> n*f(n-1)) 10;; > - : int = 3628800 http://haskell.org/hoogle/3/?q=fix Cheers, Edward From jon at ffconsultancy.com Wed Feb 24 18:53:50 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed Feb 24 17:08:23 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <1267044766-sup-1137@ezyang> References: <201002242041.01157.jon@ffconsultancy.com> <1267044766-sup-1137@ezyang> Message-ID: <201002242353.50611.jon@ffconsultancy.com> On Wednesday 24 February 2010 20:53:14 Edward Z. Yang wrote: > http://haskell.org/hoogle/3/?q=fix That leads to the following source: http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Function.html but it uses a workaround rather than extending the type system. I'm looking for an equivalent of OCaml's -rectypes that enables recursive types in Haskell (e.g. in ghci)? -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From byorgey at seas.upenn.edu Wed Feb 24 19:31:59 2010 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Feb 24 19:02:23 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <201002242353.50611.jon@ffconsultancy.com> References: <201002242041.01157.jon@ffconsultancy.com> <1267044766-sup-1137@ezyang> <201002242353.50611.jon@ffconsultancy.com> Message-ID: <20100225003159.GA28363@seas.upenn.edu> On Wed, Feb 24, 2010 at 11:53:50PM +0000, Jon Harrop wrote: > On Wednesday 24 February 2010 20:53:14 Edward Z. Yang wrote: > > http://haskell.org/hoogle/3/?q=fix > > That leads to the following source: > > http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Function.html > > but it uses a workaround rather than extending the type system. I'm looking > for an equivalent of OCaml's -rectypes that enables recursive types in > Haskell (e.g. in ghci)? Haskell has recursive types, but they are iso-recursive rather than equi-recursive; the recursion must always be guarded by a data constructor. I am not sure what you mean by saying that Data.Function contains a "workaround". What exactly are you trying to do? -Brent From cpettitt at gmail.com Wed Feb 24 21:04:02 2010 From: cpettitt at gmail.com (Chris Pettitt) Date: Wed Feb 24 20:34:27 2010 Subject: [Haskell-beginners] State Transformer Confusion Message-ID: Hello Haskell-Beginners, I'm having a fair amount of difficulty understanding the ST monad. In my basic experimentation I'm finding that I'm getting more heap allocated with STUArray than with a regular Array, which is not what I would expect. I've attached a sample program that attempts to sum a list of Ints into an array of length 1, using STUArray and UArray. The idea is based loosely on http://www.haskell.org/haskellwiki/Monad/ST, but using an array instead of an STRef. I compile using these arguments: ghc -fforce-recomp -O2 -prof -auto-all -caf-all --make sttest.hs When I run the ST-based function (sumInPlace1), I get the following output: ./sttest +RTS -sstderr 1784293664 240,944,212 bytes allocated in the heap 35,448 bytes copied during GC 4,052 bytes maximum residency (1 sample(s)) 12,332 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 459 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 0.30s ( 0.31s elapsed) GC time 0.00s ( 0.00s elapsed) RP time 0.00s ( 0.00s elapsed) PROF time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.30s ( 0.31s elapsed) %GC time 0.8% (1.2% elapsed) Alloc rate 804,910,126 bytes per MUT second Productivity 99.0% of total user, 96.5% of total elapsed While with the Array based function (sumInPlace2), I get the following output: ./sttest +RTS -sstderr 1784293664 173,627,572 bytes allocated in the heap 22,596 bytes copied during GC 3,920 bytes maximum residency (1 sample(s)) 12,464 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 333 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 0.14s ( 0.15s elapsed) GC time 0.00s ( 0.00s elapsed) RP time 0.00s ( 0.00s elapsed) PROF time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.15s ( 0.15s elapsed) %GC time 1.3% (1.9% elapsed) Alloc rate 1,200,569,571 bytes per MUT second Productivity 98.3% of total user, 94.7% of total elapsed One additional point of confusion for me: when I run either function with +RTS -hc and use hp2ps I get an empty graph. I've seen these tools work quite well before, so I suspect I'm doing something wrong now. Thanks, Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: sttest.hs Type: application/octet-stream Size: 589 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20100224/8665b2ea/sttest.obj From jon at ffconsultancy.com Wed Feb 24 22:32:25 2010 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed Feb 24 20:46:45 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <20100225003159.GA28363@seas.upenn.edu> References: <201002242041.01157.jon@ffconsultancy.com> <201002242353.50611.jon@ffconsultancy.com> <20100225003159.GA28363@seas.upenn.edu> Message-ID: <201002250332.25354.jon@ffconsultancy.com> On Thursday 25 February 2010 00:31:59 Brent Yorgey wrote: > On Wed, Feb 24, 2010 at 11:53:50PM +0000, Jon Harrop wrote: > > On Wednesday 24 February 2010 20:53:14 Edward Z. Yang wrote: > > > http://haskell.org/hoogle/3/?q=fix > > > > That leads to the following source: > > > > http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Function. > >html > > > > but it uses a workaround rather than extending the type system. I'm > > looking for an equivalent of OCaml's -rectypes that enables recursive > > types in Haskell (e.g. in ghci)? > > Haskell has recursive types, but they are iso-recursive rather than > equi-recursive; the recursion must always be guarded by a data > constructor. I am not sure what you mean by saying that Data.Function > contains a "workaround". Guarding the recursion with a constructor is the workaround I was referring to, like this: # let fix f = (fun (`X x) -> f(x (`X x))) (`X(fun (`X x) y -> f(x (`X x)) y));; val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = > What exactly are you trying to do? I'm wondering if it is possible to get this to type in Haskell without altering the code, i.e. by enabling recursive types in the compiler as I did with OCaml using -rectypes. -- Dr Jon Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?e From daniel.is.fischer at web.de Wed Feb 24 21:54:17 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 24 21:26:38 2010 Subject: [Haskell-beginners] State Transformer Confusion In-Reply-To: References: Message-ID: <201002250354.18209.daniel.is.fischer@web.de> Am Donnerstag 25 Februar 2010 03:04:02 schrieb Chris Pettitt: > Hello Haskell-Beginners, > > I'm having a fair amount of difficulty understanding the ST monad. In > my basic experimentation I'm finding that I'm getting more heap > allocated with STUArray than with a regular Array, which is not what I > would expect. And ordinarily you don't. The problem is that the STUArray suffers very badly from profiling. Compiling without -prof, the STUArray code allocates about half as much as the UArray code and takes ~42% of the time. With profiling, STUArray allocates ~40% more and takes ~50% longer than UArray. Two things: - profiling interacts badly with some optimisations, so what the profiling output says may deviate significantly from what your -O2 compiled production code actually does - some datatypes suffer more from profiling than others, so what the profiling output says for different choices of datatype may deviate significantly from how your -O2 compiled production code behaves Normally, -prof doesn't change the behaviour very much, but sometimes it does. > > One additional point of confusion for me: when I run either function > with +RTS -hc and use hp2ps I get an empty graph. I've seen these > tools work quite well before, so I suspect I'm doing something wrong > now. Too little actual heap usage and too short running time. Change the upper limit to 10 million and you should get a graph with actual bands. > > Thanks, > Chris From daniel.is.fischer at web.de Wed Feb 24 22:26:22 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 24 21:58:41 2010 Subject: [Haskell-beginners] State Transformer Confusion In-Reply-To: <201002250354.18209.daniel.is.fischer@web.de> References: <201002250354.18209.daniel.is.fischer@web.de> Message-ID: <201002250426.22683.daniel.is.fischer@web.de> Am Donnerstag 25 Februar 2010 03:54:17 schrieb Daniel Fischer: > Am Donnerstag 25 Februar 2010 03:04:02 schrieb Chris Pettitt: > > Hello Haskell-Beginners, > > > > I'm having a fair amount of difficulty understanding the ST monad. In > > my basic experimentation I'm finding that I'm getting more heap > > allocated with STUArray than with a regular Array, which is not what I > > would expect. > > And ordinarily you don't. The problem is that the STUArray suffers very > badly from profiling. Compiling without -prof, the STUArray code > allocates about half as much as the UArray code and takes ~42% of the > time. With profiling, STUArray allocates ~40% more and takes ~50% longer > than UArray. Oh, and: In the UArray code, you specified the index type as Int, in the STUArray code, you didn't specify it, so it was taken to be Integer, which slows down performance significantly, changing sumInPlace1 to sumInPlace1 :: [Int] -> Int sumInPlace1 xs = (! 0) . runSTUArray $ do a <- newArray (0 :: Int, 0) 0 forM_ xs $ \x -> do x' <- (readArray a 0) writeArray a 0 (x' + x) return a makes the STUArray code allocate ~6% of what the UArray code allocates and run in ~8% of the time, because now we get a pretty nice loop involving only unboxed Ints. If we then replace readArray and writeArray with unsafeRead and unsafeWrite, we see that the most time is spent on bounds checking, because now the STUArray loop becomes really compact and runs a good three times faster, so it's now over forty times faster than the UArray (for which using unsafeAt instead of (!) doesn't make a noticeable difference). > > Two things: > - profiling interacts badly with some optimisations, so what the > profiling output says may deviate significantly from what your -O2 > compiled production code actually does > - some datatypes suffer more from profiling than others, so what the > profiling output says for different choices of datatype may deviate > significantly from how your -O2 compiled production code behaves > > Normally, -prof doesn't change the behaviour very much, but sometimes it > does. > > > One additional point of confusion for me: when I run either function > > with +RTS -hc and use hp2ps I get an empty graph. I've seen these > > tools work quite well before, so I suspect I'm doing something wrong > > now. > > Too little actual heap usage and too short running time. Change the > upper limit to 10 million and you should get a graph with actual bands. > > > Thanks, > > Chris > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From cpettitt at gmail.com Wed Feb 24 22:47:22 2010 From: cpettitt at gmail.com (Chris Pettitt) Date: Wed Feb 24 22:17:46 2010 Subject: [Haskell-beginners] State Transformer Confusion In-Reply-To: <201002250426.22683.daniel.is.fischer@web.de> References: <201002250354.18209.daniel.is.fischer@web.de> <201002250426.22683.daniel.is.fischer@web.de> Message-ID: Hi Daniel, Thank you for your analysis. I dropped -prof from the compile and explicitly specified the index type as Int - both yielded huge improvements. These are great tips for me to keep in mind as I continue to get deeper into Haskell. Thanks, Chris On Wed, Feb 24, 2010 at 7:26 PM, Daniel Fischer wrote: > Am Donnerstag 25 Februar 2010 03:54:17 schrieb Daniel Fischer: >> Am Donnerstag 25 Februar 2010 03:04:02 schrieb Chris Pettitt: >> > Hello Haskell-Beginners, >> > >> > I'm having a fair amount of difficulty understanding the ST monad. In >> > my basic experimentation I'm finding that I'm getting more heap >> > allocated with STUArray than with a regular Array, which is not what I >> > would expect. >> >> And ordinarily you don't. The problem is that the STUArray suffers very >> badly from profiling. Compiling without -prof, the STUArray code >> allocates about half as much as the UArray code and takes ~42% of the >> time. With profiling, STUArray allocates ~40% more and takes ~50% longer >> than UArray. > > Oh, and: In the UArray code, you specified the index type as Int, in the > STUArray code, you didn't specify it, so it was taken to be Integer, which > slows down performance significantly, changing sumInPlace1 to > > sumInPlace1 :: [Int] -> Int > sumInPlace1 xs = (! 0) . runSTUArray $ do > ? ? ? ?a <- newArray (0 :: Int, 0) 0 > ? ? ? ?forM_ xs $ \x -> do > ? ? ? ? ? ?x' <- (readArray a 0) > ? ? ? ? ? ?writeArray a 0 (x' + x) > ? ? ? ?return a > > makes the STUArray code allocate ~6% of what the UArray code allocates and > run in ~8% of the time, because now we get a pretty nice loop involving > only unboxed Ints. If we then replace readArray and writeArray with > unsafeRead and unsafeWrite, we see that the most time is spent on bounds > checking, because now the STUArray loop becomes really compact and runs a > good three times faster, so it's now over forty times faster than the > UArray (for which using unsafeAt instead of (!) doesn't make a noticeable > difference). > >> >> Two things: >> - profiling interacts badly with some optimisations, so what the >> profiling output says may deviate significantly from what your -O2 >> compiled production code actually does >> - some datatypes suffer more from profiling than others, so what the >> profiling output says for different choices of datatype may deviate >> significantly from how your -O2 compiled production code behaves >> >> Normally, -prof doesn't change the behaviour very much, but sometimes it >> does. >> >> > One additional point of confusion for me: when I run either function >> > with +RTS -hc and use hp2ps I get an empty graph. I've seen these >> > tools work quite well before, so I suspect I'm doing something wrong >> > now. >> >> Too little actual heap usage and too short running time. Change the >> upper limit to 10 million and you should get a graph with actual bands. >> >> > Thanks, >> > Chris >> >> _______________________________________________ >> Beginners mailing list >> Beginners@haskell.org >> http://www.haskell.org/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From daniel.is.fischer at web.de Wed Feb 24 23:02:39 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Feb 24 22:34:58 2010 Subject: [Haskell-beginners] State Transformer Confusion In-Reply-To: <201002250426.22683.daniel.is.fischer@web.de> References: <201002250354.18209.daniel.is.fischer@web.de> <201002250426.22683.daniel.is.fischer@web.de> Message-ID: <201002250502.39917.daniel.is.fischer@web.de> Auto-replying again :) Am Donnerstag 25 Februar 2010 04:26:22 schrieb Daniel Fischer: > Am Donnerstag 25 Februar 2010 03:54:17 schrieb Daniel Fischer: > > Am Donnerstag 25 Februar 2010 03:04:02 schrieb Chris Pettitt: > > > Hello Haskell-Beginners, > > > > > > I'm having a fair amount of difficulty understanding the ST monad. > > > In my basic experimentation I'm finding that I'm getting more heap > > > allocated with STUArray than with a regular Array, which is not what > > > I would expect. > > > > And ordinarily you don't. The problem is that the STUArray suffers > > very badly from profiling. Compiling without -prof, the STUArray code > > allocates about half as much as the UArray code and takes ~42% of the > > time. With profiling, STUArray allocates ~40% more and takes ~50% > > longer than UArray. > > Oh, and: In the UArray code, you specified the index type as Int, in the > STUArray code, you didn't specify it, so it was taken to be Integer, > which slows down performance significantly, changing sumInPlace1 to > > sumInPlace1 :: [Int] -> Int > sumInPlace1 xs = (! 0) . runSTUArray $ do > a <- newArray (0 :: Int, 0) 0 > forM_ xs $ \x -> do > x' <- (readArray a 0) > writeArray a 0 (x' + x) > return a > > makes the STUArray code allocate ~6% of what the UArray code allocates > and run in ~8% of the time, because now we get a pretty nice loop > involving only unboxed Ints. If we then replace readArray and writeArray > with unsafeRead and unsafeWrite, we see that the most time is spent on > bounds checking, because now the STUArray loop becomes really compact > and runs a good three times faster, so it's now over forty times faster > than the UArray (for which using unsafeAt instead of (!) doesn't make a > noticeable difference). > To illustrate: With sumInPlace1 :: [Int] -> Int sumInPlace1 xs = (`unsafeAt` 0) . runSTUArray $ do a <- newArray (0 :: Int, 0) 0 forM_ xs $ \x -> do x' <- (unsafeRead a 0) unsafeWrite a 0 (x' + x) return a , the non-profiling code generates a tight loop, with constant allocation (*no* allocation for the enumFromTo, everything runs in registers until the end). Beautiful and fast. The profiling code can't optimise as much, the result is that the profiling code takes (for a limit of 100 million) 85 times as long as the non-profiling code. Ouch! For the UArray code, the profiling version takes only twice as long as the non-profiling version. > > Two things: > > - profiling interacts badly with some optimisations, so what the > > profiling output says may deviate significantly from what your -O2 > > compiled production code actually does > > - some datatypes suffer more from profiling than others, so what the > > profiling output says for different choices of datatype may deviate > > significantly from how your -O2 compiled production code behaves > > > > Normally, -prof doesn't change the behaviour very much, but sometimes > > it does. > > > > > One additional point of confusion for me: when I run either function > > > with +RTS -hc and use hp2ps I get an empty graph. I've seen these > > > tools work quite well before, so I suspect I'm doing something wrong > > > now. > > > > Too little actual heap usage and too short running time. Change the > > upper limit to 10 million and you should get a graph with actual > > bands. > > > > > Thanks, > > > Chris From byorgey at seas.upenn.edu Wed Feb 24 23:06:57 2010 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Wed Feb 24 22:37:20 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <201002250332.25354.jon@ffconsultancy.com> References: <201002242041.01157.jon@ffconsultancy.com> <201002242353.50611.jon@ffconsultancy.com> <20100225003159.GA28363@seas.upenn.edu> <201002250332.25354.jon@ffconsultancy.com> Message-ID: <20100225040657.GA24122@seas.upenn.edu> On Thu, Feb 25, 2010 at 03:32:25AM +0000, Jon Harrop wrote: > On Thursday 25 February 2010 00:31:59 Brent Yorgey wrote: > > On Wed, Feb 24, 2010 at 11:53:50PM +0000, Jon Harrop wrote: > > > > Haskell has recursive types, but they are iso-recursive rather than > > equi-recursive; the recursion must always be guarded by a data > > constructor. I am not sure what you mean by saying that Data.Function > > contains a "workaround". > > Guarding the recursion with a constructor is the workaround I was referring > to, like this: > > # let fix f = > (fun (`X x) -> f(x (`X x))) (`X(fun (`X x) y -> f(x (`X x)) y));; > val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = > > > What exactly are you trying to do? > > I'm wondering if it is possible to get this to type in Haskell without > altering the code, i.e. by enabling recursive types in the compiler as I did > with OCaml using -rectypes. No, it isn't. There's no equivalent of -rectypes in any Haskell compiler I'm aware of. -Brent From nicolas.pouillard at gmail.com Thu Feb 25 01:35:58 2010 From: nicolas.pouillard at gmail.com (Nicolas Pouillard) Date: Thu Feb 25 01:06:23 2010 Subject: [Haskell-beginners] Y-combinator In-Reply-To: <201002250332.25354.jon@ffconsultancy.com> References: <201002242041.01157.jon@ffconsultancy.com> <201002242353.50611.jon@ffconsultancy.com> <20100225003159.GA28363@seas.upenn.edu> <201002250332.25354.jon@ffconsultancy.com> Message-ID: <4b861a4e.0338560a.74a1.ffffd6e2@mx.google.com> On Thu, 25 Feb 2010 03:32:25 +0000, Jon Harrop wrote: > On Thursday 25 February 2010 00:31:59 Brent Yorgey wrote: > > On Wed, Feb 24, 2010 at 11:53:50PM +0000, Jon Harrop wrote: > > > On Wednesday 24 February 2010 20:53:14 Edward Z. Yang wrote: > > > > http://haskell.org/hoogle/3/?q=fix > > > > > > That leads to the following source: > > > > > > http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Function. > > >html > > > > > > but it uses a workaround rather than extending the type system. I'm > > > looking for an equivalent of OCaml's -rectypes that enables recursive > > > types in Haskell (e.g. in ghci)? > > > > Haskell has recursive types, but they are iso-recursive rather than > > equi-recursive; the recursion must always be guarded by a data > > constructor. I am not sure what you mean by saying that Data.Function > > contains a "workaround". > > Guarding the recursion with a constructor is the workaround I was referring > to, like this: > > # let fix f = > (fun (`X x) -> f(x (`X x))) (`X(fun (`X x) y -> f(x (`X x)) y));; > val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = If the reason for avoiding a data constructor is performances, then Haskell "newtype"s will help. -- Nicolas Pouillard http://nicolaspouillard.fr From john.moore54 at gmail.com Thu Feb 25 15:46:35 2010 From: john.moore54 at gmail.com (John Moore) Date: Thu Feb 25 15:16:56 2010 Subject: [Haskell-beginners] search a tree Message-ID: <4f7ad1ad1002251246n53d1dae4w21446830c01c05dd@mail.gmail.com> Hi All, I have an expression which contains several different let statements let x = 4*5 and let Y = 6+4 for example. What I want to do is traverse the tree and just return the variables. In other words I just want it to return a list of all the variables in a tree. I have a function for Var String. So would it be something like given a String -> [String] or is this expression ->String (gives back a string) Whats the best way to check or compare? Jon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100225/d26ce1a6/attachment.html From tgh at pdx.edu Thu Feb 25 15:59:05 2010 From: tgh at pdx.edu (Tyler Hayes) Date: Thu Feb 25 15:29:27 2010 Subject: [Haskell-beginners] Haskell and OpenGL Message-ID: <1267131545.3433.4.camel@ubuntu.ubuntu-domain> For anyone comfortable with OpenGl in Haskell, what is the equivalent for glutTimerFunc? Is it addTimerCallback? If so, how does it work--I've tried it and I can't seem to get it to work... It's really odd that there are straightforward implementations of callbacks for display, window resize, keyboard/mouse, etc., but not for something as common as a timer callback. Thanks, Tyler From stephen.tetley at gmail.com Thu Feb 25 16:27:27 2010 From: stephen.tetley at gmail.com (Stephen Tetley) Date: Thu Feb 25 15:57:50 2010 Subject: [Haskell-beginners] search a tree In-Reply-To: <4f7ad1ad1002251246n53d1dae4w21446830c01c05dd@mail.gmail.com> References: <4f7ad1ad1002251246n53d1dae4w21446830c01c05dd@mail.gmail.com> Message-ID: <5fdc56d71002251327u1a6bc495l7911f1f93c61b1f4@mail.gmail.com> Hi John The simplest way to extract variable names is probably with direct recursion and an accumulator - program below. Often though when working with syntax trees, you want do various things on them that share the same traversal behaviour. At this point a 'Generics' library is useful - however they are fairly complicated to use. Strafunski/StrategyLib was the original and best documented (probably not so easy to use these days as it there isn't a ready-made distribution), but there is also: Uniplate (relatively simple and well documented), Data.Generics aka SYB ('Scrap Your Boilerplate' - rather complicated but well documented, somewhat 'standard') and others generally with less documentation (e.g. Multirec, KURE). There's a paper 'Design Patterns for Functional Strategic Programming' by Joost Visser and Ralf Lammel (the a with umlauts) that is as good start as any. Best wishes Stephen module ExtractVars where data Expression = Val Double | Add Expression Expression | Subtract Expression Expression | Multiply Expression Expression | Divide Expression Expression | Var String | Let String Expression Expression extractVars :: Expression -> [String] extractVars expr = step expr [] where step (Let s e1 e2) acc = step e2 (step e1 (s:acc)) step (Add e1 e2) acc = step e2 (step e1 acc) step (Subtract e1 e2) acc = step e2 (step e1 acc) step (Multiply e1 e2) acc = step e2 (step e1 acc) step (Divide e1 e2) acc = step e2 (step e1 acc) step (Var _) acc = acc step (Val _) acc = acc demo1 = extractVars (Let "x" (Val 4) (Multiply (Var "x") (Val 4.0))) From mutilating.cauliflowers.stephen at blacksapphire.com Thu Feb 25 17:58:26 2010 From: mutilating.cauliflowers.stephen at blacksapphire.com (Stephen Blackheath [to Haskell-Beginners]) Date: Thu Feb 25 17:28:55 2010 Subject: [Haskell-beginners] Haskell and OpenGL In-Reply-To: <1267131545.3433.4.camel@ubuntu.ubuntu-domain> References: <1267131545.3433.4.camel@ubuntu.ubuntu-domain> Message-ID: <4B870092.9060002@blacksapphire.com> Tyler, Hopefully this will help. I chopped some bits out of a working program that you should be able to use as a skeleton. If you have any other OpenGL package questions, ask away. I've been using it a lot. Steve import Graphics.Rendering.OpenGL as GL import Graphics.UI.GLUT display :: IO () display = do clearColor $= bgColour clear [ColorBuffer, DepthBuffer] loadIdentity ... draw stuff here ... swapBuffers animate :: IO () animate = do postRedisplay Nothing addTimerCallback 16 $ animate main :: IO () main = do initialDisplayMode $= [DoubleBuffered, WithDepthBuffer] createWindow "Hello" -- OpenGL initialization - must be after 'createWindow' windowSize $= Size 700 700 depthFunc $= Just Less shadeModel $= Smooth lighting $= Enabled ambient (Light 0) $= Color4 0.1 0.1 0.1 (tof 1) diffuse (Light 0) $= Color4 0.9 0.9 0.9 (tof 1) light (Light 0) $= Enabled ... displayCallback $= display addTimerCallback 16 $ animate -- refresh every 16 milliseconds mainLoop Tyler Hayes wrote: > For anyone comfortable with OpenGl in Haskell, > what is the equivalent for glutTimerFunc? > Is it addTimerCallback? If so, how does it work--I've tried it and I > can't seem to get it to work... > > It's really odd that there are straightforward implementations of > callbacks for display, window resize, keyboard/mouse, etc., but not for > something as common as a timer callback. > > Thanks, > Tyler > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From uzytkownik2 at gmail.com Thu Feb 25 18:01:40 2010 From: uzytkownik2 at gmail.com (Maciej Piechotka) Date: Thu Feb 25 17:32:05 2010 Subject: [Haskell-beginners] Re: Haskell and OpenGL In-Reply-To: <1267131545.3433.4.camel@ubuntu.ubuntu-domain> References: <1267131545.3433.4.camel@ubuntu.ubuntu-domain> Message-ID: <1267138899.5465.11.camel@picard> On Thu, 2010-02-25 at 12:59 -0800, Tyler Hayes wrote: > For anyone comfortable with OpenGl in Haskell, > what is the equivalent for glutTimerFunc? > Is it addTimerCallback? If so, how does it work--I've tried it and I > can't seem to get it to work... > According to source it calls glutTimerFunc with timeout, the callback and 0. Such code seems to works for me: > import Graphics.UI.GLUT > > main = do getArgsAndInitialize > _ <- createWindow "Test" > addTimerCallback 1000 (putStrLn "Callback") > mainLoop What do you mean 'to get it to work'? Regards -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 836 bytes Desc: This is a digitally signed message part Url : http://www.haskell.org/pipermail/beginners/attachments/20100225/3939fb9d/attachment-0001.bin From flo.morphe at gmail.com Fri Feb 26 11:29:34 2010 From: flo.morphe at gmail.com (Florian Duret) Date: Fri Feb 26 11:00:14 2010 Subject: [Haskell-beginners] Parse error in pattern Message-ID: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> Hello, I try to set up a verification on the number of arguments given to my program, but keep on getting "Parse error in pattern" Here is what my code looks like: main :: IO() main = do -- On commence par ouvrir le fichier SAC en mode binaire argsList <- getArgs if (length (argsList) == 0) then do putStrLn $ "No filename given to the program.\n $ ProgramName file.sac" return () else sacFile1 <- openBinaryFile fileToOpen ReadMode ghci complains, and tells "Parse error in pattern", indicating the 'if' line number. Can you please help ? Thank you very much, Florian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100226/7dd881a8/attachment.html From magnus at therning.org Fri Feb 26 11:37:30 2010 From: magnus at therning.org (Magnus Therning) Date: Fri Feb 26 11:07:50 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> Message-ID: It doesn't look like a complete piece of code so these comments aren't backed up by running it through GHCi or anything. On Fri, Feb 26, 2010 at 16:29, Florian Duret wrote: > Hello, > > > I try to set up a verification on the number of arguments given to my > program, but keep on getting "Parse error in pattern" > Here is what my code looks like: > main :: IO() > main = do > ? ? -- On commence par ouvrir le fichier SAC en mode binaire > ? ? argsList <- getArgs > ? ? if (length (argsList) == 0) > ? ? ? ?then do > ? ? ? ? ? ? ?putStrLn $ "No filename given to the program.\n $ ProgramName > file.sac" > ? ? ? ? ? ? ?return () I believe the 'do' here is unecessary. > ? ? ? else > ? ? ? ? ? ? ?sacFile1 <- openBinaryFile fileToOpen ReadMode Here you do need a 'do' though, I believe. > > ghci complains, and tells "Parse error in pattern", indicating the 'if' line > number. > Can you please help ? > Thank you very much, > Florian > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > -- Magnus Therning (OpenPGP: 0xAB4DFBA4) magnus?therning?org Jabber: magnus?therning?org http://therning.org/magnus identi.ca|twitter: magthe From daniel.is.fischer at web.de Fri Feb 26 12:12:24 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Feb 26 11:44:39 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> Message-ID: <201002261812.25230.daniel.is.fischer@web.de> Am Freitag 26 Februar 2010 17:37:30 schrieb Magnus Therning: > It doesn't look like a complete piece of code so these comments aren't > backed up by running it through GHCi or anything. > > On Fri, Feb 26, 2010 at 16:29, Florian Duret wrote: > > Hello, > > > > > > I try to set up a verification on the number of arguments given to my > > program, but keep on getting "Parse error in pattern" > > Here is what my code looks like: > > main :: IO() > > main = do > > ? ? -- On commence par ouvrir le fichier SAC en mode binaire > > ? ? argsList <- getArgs > > ? ? if (length (argsList) == 0) It's most likely harmless for argument lists (although there are other cases), but Don't Use if (length list == 0) Never. Jamais. Niemals. Use if (null list) length has to traverse the entire list, which may take a long time. > > ? ? ? ?then do > > ? ? ? ? ? ? ?putStrLn $ "No filename given to the program.\n $ > > ProgramName file.sac" > > ? ? ? ? ? ? ?return () > > I believe the 'do' here is unecessary. > As soon as the unnecessary "return ()" is removed. > > ? ? ? else > > ? ? ? ? ? ? ?sacFile1 <- openBinaryFile fileToOpen ReadMode > > Here you do need a 'do' though, I believe. > Yes. If he binds the name sacFile1 to a value, there must come more statements after it, so the "do" is required. But it might also be wrong indentation, if the mail programme fiddled with that. > > ghci complains, and tells "Parse error in pattern", indicating the > > 'if' line number. Invoke ghci with $ ghci -ferror-spans file to see how far GHC thinks the erroneous pattern extends. From that, one can often deduce better what the problem is. > > Can you please help ? > > Thank you very much, > > Florian From flo.morphe at gmail.com Fri Feb 26 12:34:35 2010 From: flo.morphe at gmail.com (Florian Duret) Date: Fri Feb 26 12:05:14 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <201002261812.25230.daniel.is.fischer@web.de> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> <201002261812.25230.daniel.is.fischer@web.de> Message-ID: <4f1524f31002260934i760b05d1q628ab68e84870168@mail.gmail.com> It seems that both your suggestions have worked ! Thank you very much. But I still can't figure out what went wrong. My initial goal was to keep the minimum inside the if ... then ... else statement. Basically, if the list is empty, then stop. If not, then assign the argument to sacFile1, and go on with the rest. Here is what it looks like now: module Main () where import System.IO import System.Environment(getArgs) import Data.Char(intToDigit) import SAC_Type import SAC_IO main :: IO() main = do -- On commence par ouvrir le fichier SAC en mode binaire argsList <- getArgs if (null argsList) then putStrLn $ "No filename given to the program.\n $ ProgramName file.sac" else do sacFile1 <- openBinaryFile (head argsList) ReadMode position <- hTell sacFile1 putStrLn $ "Position 1: " ++ [intToDigit( fromInteger (position) )] hSeek sacFile1 AbsoluteSeek 440 position2 <- hTell sacFile1 putStrLn $ "Position 2: " ++ [intToDigit( fromInteger (position2) )] -- A la fin, il faut evidemment le fermer hClose sacFile1 Thank you, Danke, ??, merci, etc... 2010/2/26 Daniel Fischer > Am Freitag 26 Februar 2010 17:37:30 schrieb Magnus Therning: > > It doesn't look like a complete piece of code so these comments aren't > > backed up by running it through GHCi or anything. > > > > On Fri, Feb 26, 2010 at 16:29, Florian Duret > wrote: > > > Hello, > > > > > > > > > I try to set up a verification on the number of arguments given to my > > > program, but keep on getting "Parse error in pattern" > > > Here is what my code looks like: > > > main :: IO() > > > main = do > > > -- On commence par ouvrir le fichier SAC en mode binaire > > > argsList <- getArgs > > > if (length (argsList) == 0) > > It's most likely harmless for argument lists (although there are other > cases), but > > Don't Use > > if (length list == 0) > > Never. Jamais. Niemals. > > Use > > if (null list) > > length has to traverse the entire list, which may take a long time. > > > > then do > > > putStrLn $ "No filename given to the program.\n $ > > > ProgramName file.sac" > > > return () > > > > I believe the 'do' here is unecessary. > > > > As soon as the unnecessary "return ()" is removed. > > > > else > > > sacFile1 <- openBinaryFile fileToOpen ReadMode > > > > Here you do need a 'do' though, I believe. > > > > Yes. If he binds the name sacFile1 to a value, there must come more > statements after it, so the "do" is required. > > But it might also be wrong indentation, if the mail programme fiddled with > that. > > > > ghci complains, and tells "Parse error in pattern", indicating the > > > 'if' line number. > > Invoke ghci with > > $ ghci -ferror-spans file > > to see how far GHC thinks the erroneous pattern extends. From that, one can > often deduce better what the problem is. > > > > Can you please help ? > > > Thank you very much, > > > Florian > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100226/30bb8500/attachment.html From daniel.is.fischer at web.de Fri Feb 26 16:57:03 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Feb 26 16:29:15 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <4f1524f31002260934i760b05d1q628ab68e84870168@mail.gmail.com> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> <201002261812.25230.daniel.is.fischer@web.de> <4f1524f31002260934i760b05d1q628ab68e84870168@mail.gmail.com> Message-ID: <201002262257.04032.daniel.is.fischer@web.de> Am Freitag 26 Februar 2010 18:34:35 schrieb Florian Duret: > It seems that both your suggestions have worked ! Thank you very much. > But I still can't figure out what went wrong. Did you change anything besides removing the "do" and "return ()" from the then-branch and insert the "do" in the else-branch? If not, you've been bitten by a somewhat less than obvious aspect of layout - although it's pretty clear with an explanation. A new layout-block isn't opened by a larger indentation, but by the keywords do, let, of and where. So, when you write ... = do xxx if blah then do foo bar else baz zap the "do" after the then opens a new layout-block inside the big do-block, since you didn't insert an explicit brace. The indentation level thereof is determined by the 'f' of "foo", bar is indented to the same level as foo, so it's a new expression in that same block. The else is indented less than the foo, so that ends the inner layout-block and we return to the layout-block of the big do-block. The indentation level thereof is determined by the first 'x', and the "if" is indented to the same level. The else, the baz and the zap are all indented further than the if, so they all belong to the if-expression (as intended). But since there's no "do" after the "else", all that is on one logical line, it's parsed as ... = do xxx if blah then do { foo; bar } else baz zap Not what was intended, but it parses just fine. Now you didn't have baz zap but baz <- bong zap and since we're still having only one logical line for the if-expression, the parser sees that as ... = do xxx if blah then do { foo; bar } else baz <- bong zap But the syntax is pattern <- expression so the parser tries to parse if blah then do { foo; bar } else baz as a pattern. But it doesn't conform to the pattern productions, hence the parse error. > > My initial goal was to keep the minimum inside the if ... then ... else > statement. Basically, if the list is empty, then stop. If not, then > assign the argument to sacFile1, and go on with the rest. It would be cleanest to have realWork :: FileName -> IO () realWork file = do sacFile1 <- openBinaryFile file ReadMode ... main :: IO () main = do argList <- getArgs case argList of [] -> putStrLn "No filename ..." (f:_) -> realWork f or if null argList then putStrLn "..." else realWork (head argList) , je pense. > > Here is what it looks like now: > module Main () where > > import System.IO > import System.Environment(getArgs) > import Data.Char(intToDigit) > > import SAC_Type > import SAC_IO > > main :: IO() > main = do > -- On commence par ouvrir le fichier SAC en mode binaire > argsList <- getArgs > if (null argsList) > then > putStrLn $ "No filename given to the program.\n $ > ProgramName file.sac" > else do > sacFile1 <- openBinaryFile (head argsList) ReadMode > > position <- hTell sacFile1 > putStrLn $ "Position 1: " ++ [intToDigit( fromInteger > (position) )] > > hSeek sacFile1 AbsoluteSeek 440 > position2 <- hTell sacFile1 > putStrLn $ "Position 2: " ++ [intToDigit( fromInteger > (position2) )] I don't think that's what you really want: Prelude Data.Char> intToDigit 440 *** Exception: Char.intToDigit: not a digit 440 perhaps you wanted putStrLn $ "Position 2: " ++ show position2 ? > > -- A la fin, il faut evidemment le fermer > hClose sacFile1 > > > Thank you, Danke, ??, merci, etc... From flo.morphe at gmail.com Sat Feb 27 07:17:38 2010 From: flo.morphe at gmail.com (Florian Duret) Date: Sat Feb 27 06:48:20 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <201002262257.04032.daniel.is.fischer@web.de> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> <201002261812.25230.daniel.is.fischer@web.de> <4f1524f31002260934i760b05d1q628ab68e84870168@mail.gmail.com> <201002262257.04032.daniel.is.fischer@web.de> Message-ID: <4f1524f31002270417l70d8deacl723e8c4dc5c32cf4@mail.gmail.com> Thank you Daniel, this helps a lot ! As you can guess, I come from the imperative world, but want to discover functionnal languages (thanks to xmonad). Thank you very much for your explainations. I think I will fall in that trap again, but next time, I should be able to fix it myself. I still don't understand exactly what lies behind, but start to get the picture. I didn't change anything besides the position of the 'do' and the deletion of the 'return ()'. I will modify the code with the realWork function as you suggested. I looks much nicer. As of the last problem, with the intToDigit function. I already knew about the bug. I actually knew it wouldn't work since it is takes only argument from 0 to 15... Well, that was lazy from me. I just wanted to write the statement so that I don't forget it. Danke sehr. 2010/2/26 Daniel Fischer > Am Freitag 26 Februar 2010 18:34:35 schrieb Florian Duret: > > It seems that both your suggestions have worked ! Thank you very much. > > But I still can't figure out what went wrong. > > Did you change anything besides removing the "do" and "return ()" from the > then-branch and insert the "do" in the else-branch? > If not, you've been bitten by a somewhat less than obvious aspect of layout > - although it's pretty clear with an explanation. > A new layout-block isn't opened by a larger indentation, but by the > keywords do, let, of and where. > So, when you write > > ... = do > xxx > if blah > then do > foo > bar > else > baz > zap > > the "do" after the then opens a new layout-block inside the big do-block, > since you didn't insert an explicit brace. The indentation level thereof > is determined by the 'f' of "foo", bar is indented to the same level as > foo, so it's a new expression in that same block. > The else is indented less than the foo, so that ends the inner layout-block > and we return to the layout-block of the big do-block. The indentation > level thereof is determined by the first 'x', and the "if" is indented to > the same level. > The else, the baz and the zap are all indented further than the if, so they > all belong to the if-expression (as intended). > But since there's no "do" after the "else", all that is on one logical > line, it's parsed as > > ... = do > xxx > if blah then do { foo; bar } else baz zap > > Not what was intended, but it parses just fine. > > Now you didn't have > > baz > zap > > but > > baz <- bong > zap > > and since we're still having only one logical line for the if-expression, > the parser sees that as > > ... = do > xxx > if blah then do { foo; bar } else baz <- bong zap > > But the syntax is > > pattern <- expression > > so the parser tries to parse > > if blah then do { foo; bar } else baz > > as a pattern. But it doesn't conform to the pattern productions, hence the > parse error. > > > > > My initial goal was to keep the minimum inside the if ... then ... else > > statement. Basically, if the list is empty, then stop. If not, then > > assign the argument to sacFile1, and go on with the rest. > > It would be cleanest to have > > realWork :: FileName -> IO () > realWork file = do > sacFile1 <- openBinaryFile file ReadMode > ... > > main :: IO () > main = do > argList <- getArgs > case argList of > [] -> putStrLn "No filename ..." > (f:_) -> realWork f > > or > > if null argList > then putStrLn "..." > else realWork (head argList) > > , je pense. > > > > > Here is what it looks like now: > > module Main () where > > > > import System.IO > > import System.Environment(getArgs) > > import Data.Char(intToDigit) > > > > import SAC_Type > > import SAC_IO > > > > main :: IO() > > main = do > > -- On commence par ouvrir le fichier SAC en mode binaire > > argsList <- getArgs > > if (null argsList) > > then > > putStrLn $ "No filename given to the program.\n $ > > ProgramName file.sac" > > else do > > sacFile1 <- openBinaryFile (head argsList) ReadMode > > > > position <- hTell sacFile1 > > putStrLn $ "Position 1: " ++ [intToDigit( fromInteger > > (position) )] > > > > hSeek sacFile1 AbsoluteSeek 440 > > position2 <- hTell sacFile1 > > putStrLn $ "Position 2: " ++ [intToDigit( fromInteger > > (position2) )] > > I don't think that's what you really want: > > Prelude Data.Char> intToDigit 440 > *** Exception: Char.intToDigit: not a digit 440 > > perhaps you wanted > > putStrLn $ "Position 2: " ++ show position2 > > ? > > > > > -- A la fin, il faut evidemment le fermer > > hClose sacFile1 > > > > > > Thank you, Danke, ??, merci, etc... > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100227/1e28fbd6/attachment-0001.html From tom.davie at gmail.com Sat Feb 27 09:41:29 2010 From: tom.davie at gmail.com (Tom Davie) Date: Sat Feb 27 09:11:46 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <201002261812.25230.daniel.is.fischer@web.de> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> <201002261812.25230.daniel.is.fischer@web.de> Message-ID: <8b70a98a1002270641h4f9e2ed9qe2e529e5fafe8eee@mail.gmail.com> On Fri, Feb 26, 2010 at 5:12 PM, Daniel Fischer wrote: > Am Freitag 26 Februar 2010 17:37:30 schrieb Magnus Therning: > > It doesn't look like a complete piece of code so these comments aren't > > backed up by running it through GHCi or anything. > > > > On Fri, Feb 26, 2010 at 16:29, Florian Duret > wrote: > > > Hello, > > > > > > > > > I try to set up a verification on the number of arguments given to my > > > program, but keep on getting "Parse error in pattern" > > > Here is what my code looks like: > > > main :: IO() > > > main = do > > > -- On commence par ouvrir le fichier SAC en mode binaire > > > argsList <- getArgs > > > if (length (argsList) == 0) > > It's most likely harmless for argument lists (although there are other > cases), but > > Don't Use > > if (length list == 0) > > Never. Jamais. Niemals. > > Use > > if (null list) > > length has to traverse the entire list, which may take a long time. While the advice here is sound 90% of the time, it's evidence of falling into the trap of underestimating lazyness. If 0 and length list are both of type Nat, the first will be exactly as fast as the second. Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100227/e3ecf912/attachment.html From daniel.is.fischer at web.de Sat Feb 27 10:41:17 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sat Feb 27 10:13:28 2010 Subject: [Haskell-beginners] Parse error in pattern In-Reply-To: <8b70a98a1002270641h4f9e2ed9qe2e529e5fafe8eee@mail.gmail.com> References: <4f1524f31002260829j48bcbda7x17017df9270fe3cd@mail.gmail.com> <201002261812.25230.daniel.is.fischer@web.de> <8b70a98a1002270641h4f9e2ed9qe2e529e5fafe8eee@mail.gmail.com> Message-ID: <201002271641.17340.daniel.is.fischer@web.de> Am Samstag 27 Februar 2010 15:41:29 schrieb Tom Davie: > While the advice here is sound 90% of the time, it's evidence of falling > into the trap of underestimating lazyness. ?If 0 and length list are > both of type Nat, the first will be exactly as fast as the second. > > Bob As it is, we have length :: [a] -> Int Of course, an implementation with a lazy Int type is thinkable, but for the time being, it's a pretty safe bet that Int comparisons need complete evaluation of the arguments. (In GHC, you can use rewrite rules to avoid it, but if you think of that, you wouldn't write "length xs == k" unless you really mean it in the first place.) Most of the uses of "length xs == k" are due to the fact that people are used to strict list-like structures carrying their length with them and not to singly linked lazy lists of unknown length, I believe. So I'd say the advice is sound 100% of the time, though often the lists are so short that it's not a big deal. Thus the advice may be important less than 25% of the time. Now, genericLength is a different case. "genericLength xs == k" is a dangerous thing if used at strict types, but perfectly fine for lazy naturals. P.S.: Tom, I'm curious, why do you sign as Bob? From edgar.klerks at gmail.com Sun Feb 28 16:06:06 2010 From: edgar.klerks at gmail.com (edgar klerks) Date: Sun Feb 28 15:36:40 2010 Subject: [Haskell-beginners] Small question Message-ID: <7c40819c1002281306q793cfac6u93e48b204c6ea7a5@mail.gmail.com> Hi there, I have created a function mkc: mkc :: (a -> b) -> a -> m b mkc f = (\x -> return $ f x) which works wonderful in statements like: number <- many1 digit >>= mkc(read) But somehow I think this function should already exist, it is some kind of lifting. If it exist where can I find it? Or is there a reason, why it isn't in prelude, because it is more elegant way to solve this problem. Thanks in advance, Edgar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100228/aa53dbe3/attachment.html From alexander.dunlap at gmail.com Sun Feb 28 16:14:52 2010 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Sun Feb 28 15:45:24 2010 Subject: [Haskell-beginners] Small question In-Reply-To: <7c40819c1002281306q793cfac6u93e48b204c6ea7a5@mail.gmail.com> References: <7c40819c1002281306q793cfac6u93e48b204c6ea7a5@mail.gmail.com> Message-ID: <57526e771002281314r65a0477cm93260fa1933a85@mail.gmail.com> On Sun, Feb 28, 2010 at 1:06 PM, edgar klerks wrote: > Hi there, > > I have created a function mkc: > > mkc :: (a -> b) -> a -> m b > mkc f = (\x -> return $ f x) > > which works wonderful in statements like: > > number <- many1 digit >>= mkc(read) > > But somehow I think this function should already exist, it is some kind of > lifting. If it exist where can I find it? Or is there a reason, why it isn't > in prelude, because it is more elegant way to solve this problem. > > Thanks in advance, > > Edgar > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > > For something like this, we generally do fmap read (many1 digit) fmap is equivalent to liftM from Control.Monad and liftA from Control.Applicative. It has type Functor f => (a -> b) -> (f a -> f b). All monads can be functors (and all of the standard ones are), so it can generally be used as a function (a -> b) -> (m a -> m b) for a monad m. liftM has the type Monad m => (a -> b) -> (m a -> m b). Alex Alex From felipe.lessa at gmail.com Sun Feb 28 16:16:54 2010 From: felipe.lessa at gmail.com (Felipe Lessa) Date: Sun Feb 28 15:47:08 2010 Subject: [Haskell-beginners] Small question In-Reply-To: <7c40819c1002281306q793cfac6u93e48b204c6ea7a5@mail.gmail.com> References: <7c40819c1002281306q793cfac6u93e48b204c6ea7a5@mail.gmail.com> Message-ID: <20100228211654.GA15230@kira.casa> On Sun, Feb 28, 2010 at 10:06:06PM +0100, edgar klerks wrote: > I have created a function mkc: > > mkc :: (a -> b) -> a -> m b > mkc f = (\x -> return $ f x) Actually the type is mkc :: Monad m => (a -> b) -> a -> m b and you could define it as mkc = (return .) However, we usually don't need this function. > which works wonderful in statements like: > > number <- many1 digit >>= mkc(read) We prefer to right number <- fmap read (many1 digit) or, even better yet import Control.Applicative number <- read <$> many1 digit Note that (<$>) :: Functor f => (a -> b) -> (f a -> f b) f <$> x = fmap f x Cheers, -- Felipe. From lazyswamp at gmail.com Sun Feb 28 02:54:38 2010 From: lazyswamp at gmail.com (Kwanghoon Choi) Date: Sun Feb 28 16:16:33 2010 Subject: [Haskell-beginners] Maximum length of a GHCi command? Message-ID: <2d44ccdd1002272354q3dcf11ddse2bff6f22e6251d2@mail.gmail.com> Dear Haskeller, I have a little issue in using GHCi as follows: === Prelude> length "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" :1:254: lexical error in string/character literal at character '\EOT' === It seems to me that GHCi doesn't allow me to type more than some specified length of a command. Is this interpretation correct? How can I make it longer? This issue is quite important at least to me. My tool is just a simple Haskell program. I don't like to add any extra interactive environment, but I like to just use GHCi as an interactive environment for my tool. I strongly believe that this ides is pervasive among many haskellers. Thanks in advance for your help/feedback in advance. Kwanghoon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20100228/4cf04f4d/attachment.html From ehamberg at gmail.com Sun Feb 28 16:51:47 2010 From: ehamberg at gmail.com (Erlend Hamberg) Date: Sun Feb 28 16:20:39 2010 Subject: [Haskell-beginners] Maximum length of a GHCi command? In-Reply-To: <2d44ccdd1002272354q3dcf11ddse2bff6f22e6251d2@mail.gmail.com> References: <2d44ccdd1002272354q3dcf11ddse2bff6f22e6251d2@mail.gmail.com> Message-ID: <201002282251.55654.ehamberg@gmail.com> On Sunday 28. February 2010 08.54.38 Kwanghoon Choi wrote: > === > Prelude> length > "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > aaaaaaaaaaaaaaaaaaaaaaaaaa" :1:254: > lexical error in string/character literal at character '\EOT' > === > > It seems to me that GHCi doesn't allow me to type more than some specified > length of a command. Is this interpretation correct? How can I make it > longer? Which platform is this? That works perfectly here. Even 1000 characters seems to work. If this is on *nix, maybe it has something to do with readline / editline / whatever is used now? -- Erlend Hamberg ?Everything will be ok in the end. If its not ok, its not the end.? GPG/PGP: 0xAD3BCF19 45C3 E2E7 86CA ADB7 8DAD 51E7 3A1A F085 AD3B CF19 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part. Url : http://www.haskell.org/pipermail/beginners/attachments/20100228/c280120c/attachment.bin From daniel.is.fischer at web.de Sun Feb 28 17:00:09 2010 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Sun Feb 28 16:32:17 2010 Subject: [Haskell-beginners] Maximum length of a GHCi command? In-Reply-To: <2d44ccdd1002272354q3dcf11ddse2bff6f22e6251d2@mail.gmail.com> References: <2d44ccdd1002272354q3dcf11ddse2bff6f22e6251d2@mail.gmail.com> Message-ID: <201002282300.09992.daniel.is.fischer@web.de> Am Sonntag 28 Februar 2010 08:54:38 schrieb Kwanghoon Choi: > Dear Haskeller, > > I have a little issue in using GHCi as follows: > > === > Prelude> length > "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >aaaaaaaaaaaaaaaaaaaaaaaaaaaa" :1:254: > lexical error in string/character literal at character '\EOT' > === Hm, Prelude> length "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 99 Prelude> length "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 549 And it shouldn't get an \EOT anyway, also column 254 is way past the String. > > It seems to me that GHCi doesn't allow me to type more than some > specified length of a command. There's some limit (memory, terminal buffer), but in practice, you shouldn't ever come near it. > Is this interpretation correct? How can I make it longer? > > This issue is quite important at least to me. My tool is just a simple > Haskell program. I don't like to add any extra interactive environment, > but I like to just use GHCi as an interactive environment for my tool. I > strongly believe that this ides is pervasive among many haskellers. So, ghci got the command from your tool and not from you typing at the prompt? Then it seems your tool outputs unwanted \EOT characters, it might be worth to check. > > Thanks in advance for your help/feedback in advance. > > Kwanghoon