From apfelmus at quantentunnel.de Mon Dec 1 05:02:08 2008 From: apfelmus at quantentunnel.de (Apfelmus, Heinrich) Date: Mon Dec 1 04:55:48 2008 Subject: [Haskell-beginners] Re: Memoization In-Reply-To: <719881900811290445o77fa6b77pd34870504be1a662@mail.gmail.com> References: <719881900811290445o77fa6b77pd34870504be1a662@mail.gmail.com> Message-ID: abdullah abdul Khadir wrote: > Hi, > I am a student and we had an assignment in Haskell. The question, was > given a string of the form "1-2+3*5-7+4-6+3" i.e., any sequence of integers > as well as some operators between them we had to find a maximum possible > value for the expression as well as the expression itself . So for maxval > "1-2+3*5-7+4-6+3" it is (76,"(1-((2+3)*((5-(7+4))-(6+3))))"). The function > we had to write was maxval :: String -> (Int,String). For further details on > the question, have a look at our sir's web page > here. > > I solved the question, we had to use memoization, and submitted the > solution. It is given below. Now the problem is I am just wondering if it > can be solved in a better manner. Translation : Is there some way in Haskell > to do it in a more simpler way and as well as to reduce the number of lines > of the program. Yes, your solution can be made more beautiful. Let me show how. First of all, we should separate *parsing* the input into a list of numbers and operations from *computing* the result. maxval :: String -> (Int, String) maxval = compute . parse In other words, parse extracts the numbers and arithmetic operations from the input. One example implementation is type Op = Char parse :: String -> ([Int], [Op]) parse [] = ([],[]) parse s = let (n,s2) = parseInt s in case s2 of [] -> ([n],[]) op:s3 -> let (ns,ops) = parse s3 in (n:ns,op:ops) parseInt :: String -> (Int, String) parseInt s = (n, s') where (digits, s') = span isDigit s n = foldl (\x c -> 10*x + fromDigit c) 0 digits fromDigit c = ord c - ord '0' but it's more complicated then necessary. We should at least use the reads functions from the Prelude . And in any case, *parser combinators* are the best way to parse something. But for now, the straightforward way above shall suffice. Second, we can considerably clarify things by defining new types. Our first abstraction is the *expression* type Expr = (Int,String) value :: Expr -> Int value = fst which consists of a value and its textual representation. For instance, (20, "((6*3)+2)") (30, "(6*(3+2))") are expressions. We can combine two expression by applying one of our arithmetic operations both to the value and the textual representation applyExpr :: Op -> Expr -> Expr -> Expr applyExpr op (x,ex) (y,ey) = (f op x y, "(" ++ ex ++ [op] ++ ey ++ ")") where f '+' = (+) f '-' = (-) f '*' = (*) Our main algorithm will choose maximal and minimal values from a set of possible expressions. Therefore, we introduce the following type data MinMax = M Expr Expr deriving (Show) which represents a range of values by recording expressions of minimal and maximal value. maxexpr :: MinMax -> Expr maxexpr (M _ e) = e We can merge two such ranges ("union") by choosing the lower first and the higher second part: merge :: MinMax -> MinMax -> MinMax merge (M x y) (M x2 y2) = M emin emax where emin = if value x < value x2 then x else x2 emax = if value y > value y2 then y else y2 merges :: [MinMax] -> MinMax merges = foldr1 merge fromExpr :: Expr -> MinMax fromExpr e = M e e Now, we also want to apply arithmetic expressions to these ranges. For '+','-' and '*', the following function does the right thing: applyMinMax :: Op -> MinMax -> MinMax -> MinMax applyMinMax op (M x y) (M x2 y2) = merges [fromExpr (applyExpr op z z2) | z<-[x,y], z2<-[x2,y2]] With these preliminaries, we can now express the algorithm. The main ingredient is a function (f :: Int -> Int -> MinMax) that calculates the range of possible values for expression that only utilize numbers between the positions i and j in the list. And as common in dynamic programming, we employ a memo table to store the intermediate results. compute :: ([Int], [Op]) -> Expr compute (xs,ops) = maxexpr (f 1 n) where n = length xs f = memoize n f' f' i j | i == j = let x = xs !! (i-1) e = (x,show x) in fromExpr e | otherwise = merges [applyMinMax (ops !! (k-1)) (f i k) (f (k+1) j) | k <- [i..(j-1)]] Where exactly is the memo table? It's hidden in memoize :: Int -> (Int -> Int -> a) -> (Int -> Int -> a) memoize n f = \i j -> table ! (i,j) where table = array ((1,1),(n,n)) [((i,j), f i j) | i<-[1..n], j<-[1..n]] which takes a function of two arguments from 1 to n and tabulates its values in an array. (You need to import Data.Array for the arrays.) In other words, f tabulates the results of f' which in turn uses the tabulated values returned by f to compute its results. Thanks to lazy evaluation, this "tabulate the result before it's available" works. To summarize, the key points of the new solution are * Parse input. * Abstractions. * Memoization is a simple higher order function. But there is more. Namely, there are many different ways to implement the memoization. I used an array, you were asked to use a linked list. The former is O(1) the latter O(n). There is a way to do it with plain trees but still O(1), see also section 3 of Richard Bird and Ralf Hinze. "Trouble Shared is Trouble Halved" http://www.informatik.uni-bonn.de/~ralf/publications/HW2003.pdf And there is even more! Namely, we knew that the problem is an instance of dynamic programming, we knew the algorithm before implementing it. But how to find the algorithm in the first place? Well, the usual answer is "by thinking hard". However, there are very systemic ways to derive dynamic programming algorithms from just the problem specification! In a sense, much of the work of R. Bird centers this topic. The book "Algebra of Programming" http://web.comlab.ox.ac.uk/oucl/research/pdt/ap/pubs.html#Bird-deMoor96:Algebra is one of the cornerstones. The systematic derivation of dynamic programming algorithms has been rediscovered in a more direct but less general fashion http://bibiserv.techfak.uni-bielefeld.de/adp/ Regards, H. Apfelmus From DekuDekuplex at Yahoo.com Wed Dec 3 01:39:41 2008 From: DekuDekuplex at Yahoo.com (Benjamin L.Russell) Date: Wed Dec 3 01:33:13 2008 Subject: [Haskell-beginners] Re: ANNOUNCE: Haskell Communities and Activities Report (15th ed., November 2008) References: <492F9701.9010707@tcs.inf.tu-dresden.de> Message-ID: <24acj4l7kn1gu5l8eu4lmkg5k2c2nk6jit@4ax.com> On Fri, 28 Nov 2008 16:15:30 -0800, Don Stewart wrote: >Good work! > >It is always interesting to see the secret Haskell projects that only >get announced via the HCAR. Things not on haskell@ or on hackage. > >For example, this under-the-radar project: > > http://www.haskell.org/communities/11-2008/html/report.html#sect7.7 > > 7.7 IVU Traffic Technologies AG Rostering Group > >Haskell to solve constraints on EU bus timetables! In production use! Speaking of production use, one type of project that would be interesting would be a study examining how Haskell can increase programmer productivity for production use for programmers who are not necessarily gifted in programming, but whose forte may lie in another field and who are very interested in functional programming; i.e., some type of tabulated data (preferably a graph, although a table would work, too) of data quantifying how useful Haskell is in allowing one whose forte may not necessarily be in programming (say, a physicist, mathematician, or even a translator who happens to have an algorithmically-focused computer science degree) to equal or excel the productivity of, say, a gifted C/C++ programmer in, say, setting up a commercial Web site. The reason is that recently, there has been news of people in academia leaving for other realms because of worsening conditions (see "As strikes begin, lecturer quits to become plumber" at http://www.guardian.co.uk/uk/2004/feb/24/lecturerspay.highereducation, and "Why I am Not a Professor OR The Decline and Fall of the British University" at http://www.lambdassociates.org/blog/decline.htm). Up to know, my dream was to publish a paper on type theory to motivate study of Haskell, but now it looks like I may need to aim for creating a commercial Web site. However, I am not sure of being able to compete with commercial Web sites, because I am more of a writer/translator who happens to like functional programming than a real-life programmer. I've already seen such articles as "Why Functional Programming Matters" (see http://www.md.chalmers.se/~rjmh/Papers/whyfp.html), "Why Haskell Matters" (see http://www.haskell.org/haskellwiki/Why_Haskell_matters), and "Beating the Averages" (see http://www.paulgraham.com/avg.html). However, these essays tend to focus on how a functional language FL is structurally better than non-functional languages NFL in general, without specifying the skill-level of the programmer. Instead, it would be interesting to find the minimum skill-level s necessary for, say, somebody whose forte is not in programming, but who, say, studies functional programming as a hobby, to use Haskell as a tool in achieving a productivity level equivalent to that of a gifted C/C++ programmer. To sum: Can a theoretically-minded Haskell student who studies Haskell out of interest in type theory compete with star C/C++ programmers in developing, say, commercial Web sites? This is not quite clear, because even if Haskell can increase programmer productivity by tenfold, a star programmer can also be more productive than an average programmer by tenfold. How risky is this challenge? -- Benjamin L. Russell > >-- Don > > >voigt: >> On behalf of the many, many contributors, I am pleased to announce >> that the >> >> Haskell Communities and Activities Report >> (15th edition, November 2008) >> >> http://www.haskell.org/communities/ >> >> is now available from the Haskell Communities home page in PDF and >> HTML formats. -- Benjamin L. Russell / DekuDekuplex at Yahoo dot com http://dekudekuplex.wordpress.com/ Translator/Interpreter / Mobile: +011 81 80-3603-6725 "Furuike ya, kawazu tobikomu mizu no oto." -- Matsuo Basho^ From martin.hofmann at uni-bamberg.de Wed Dec 3 04:25:07 2008 From: martin.hofmann at uni-bamberg.de (Martin Hofmann) Date: Wed Dec 3 04:15:53 2008 Subject: [Haskell-beginners] What causes <>? Message-ID: <1228296307.6022.4.camel@ios.cogsys.wiai.uni-bamberg.de> I've already posted this mail on haskell-cafe, but apparently the subject suggested a too simple question, so I try it here again. I am picking up a discussion with the same topic from haskell-users on 8th November. Thunks with reference on themselves was mentioned as main reason for <>. > A safe recursive definition would be > let x = Foo (x+1) > However, if you leave out the constructor, > let x = x + 1 > you get a <> (or a deadlock). > Are there any other reasons? I am trying to debug monadic code which stores state information in a record maintaining several Data.Maps, but in vain so far. A state is modified/changed in several steps by a compound function i.e. changeA $ changeB $ changeC state Could this also lead to a deadlock? If so, can I prevent this using CPS? If the state transformation is the main purpose/computation of the monad at all, is it better to use CPS? Is code using mtl, records or Data.Map more prone to <> or does this not matter at all. How can I identify self-referencing thunks more easily? Is there any rule of thumb to prevent <>? Are there any less obvious newbie mistakes causing < then the one above? Sorry, a lot of questions at once, but I am kind of helpless because I can't find any reason of my <>, so any comments, experience, and tips are highly appreciated. Thanks, Martin From jeedward at yahoo.com Wed Dec 3 20:57:21 2008 From: jeedward at yahoo.com (John Edward) Date: Wed Dec 3 20:53:23 2008 Subject: [Haskell-beginners] Special session on Haskell language Message-ID: <480491.51274.qm@web45908.mail.sp1.yahoo.com> Special session on Haskell language at MULTICONF-09 call for papers ? Special session on Haskell language will be held at the 2009 Multi Conference in Computer Science, Information Technology and Control systems and Computational Science and Computer Engineering (MULTICONF-09) (website: http://www.PromoteResearch.org) and it will be held during July 13-16 2009 in Orlando, FL, USA. We invite draft paper submissions. The event consists of the following conferences: ????????? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-09) ????????? International Conference on Automation, Robotics and Control Systems (ARCS-09) ????????? International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-09) ????????? International Conference on Enterprise Information Systems and Web Technologies (EISWT-09) ????????? International Conference on High Performance Computing, Networking and Communication Systems (HPCNCS-09) ????????? International Conference on Information Security and Privacy (ISP-09) ????????? International Conference on Recent Advances in Information Technology and Applications (RAITA-09) ????????? International Conference on Software Engineering Theory and Practice (SETP-09) ????????? International Conference on Theory and Applications of Computational Science (TACS-09) ????????? International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-09) ? The website http://www.PromoteResearch.org? contains more details. ? Sincerely John Edward Publicity committee ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081203/2b0f6236/attachment-0001.htm From wojtowicz.norbert at gmail.com Thu Dec 4 07:07:06 2008 From: wojtowicz.norbert at gmail.com (Norbert Wojtowicz) Date: Thu Dec 4 07:00:26 2008 Subject: [Haskell-beginners] gtk2hs not rendering drawingArea Message-ID: Hello, I'm having problems getting a drawingArea to render, I've narrowed the program down to the following skeleton. Any suggestions on what I'm doing wrong? The label gets updated correctly, but the drawingArea just remains gray as if it was never rendered. I'm including an entire compilable skeleton in case someone wants to help me debug it. (I have a feeling I'm just missing something very obvious...) Thanks in advance, Norbert skeletonTest.hs: module Main where import Graphics.UI.Gtk -- hiding (fill) import Graphics.UI.Gtk.Glade import Graphics.Rendering.Cairo.SVG import Graphics.Rendering.Cairo import Control.Monad main = do initGUI let gFile = "brainSpin.glade" windowXmlM <- xmlNew gFile let windowXml = case windowXmlM of (Just windowXml) -> windowXml Nothing -> error "Can't find the glade file \"brainSpin.glade\" in the current directory" window <- xmlGetWidget windowXml castToWindow "brainSpinMain" onDestroy window mainQuit label <- xmlGetWidget windowXml castToLabel "label1" drawArea <- xmlGetWidget windowXml castToDrawingArea "drawArea" widgetShowAll window labelSetText label "foo" -- THIS is the offending code. Originally I was working with SVGs, but I simplified -- it to this, just to track down the problem. It seems any Render () does not -- get updated in the drawArea let r = do setSourceRGB 0 0 0 paint drawin <- widgetGetDrawWindow drawArea renderWithDrawable drawin r mainGUI brainSpin.glade: True True label True 1 From Sayali.Kulkarni at kpitcummins.com Thu Dec 4 07:12:42 2008 From: Sayali.Kulkarni at kpitcummins.com (Sayali Kulkarni) Date: Thu Dec 4 22:01:44 2008 Subject: [Haskell-beginners] Profiling haskell code In-Reply-To: <20081118121714.GA9052@seas.upenn.edu> Message-ID: <82C3BC9106BCE149B63464D79D0A22FD07C6AAED@sohm.kpit.com> Hey thanks Brent. This helped. I have one more question now. Consider I have two functions 1. gives me a range of numbers in an array. 2. has to get an array input for further process. Then how can I get the array generated by the first function tobe the input of the second function? Regards, Sayali -----Original Message----- From: Brent Yorgey [mailto:byorgey@seas.upenn.edu] Sent: Tuesday, November 18, 2008 5:47 PM To: Sayali Kulkarni Subject: Re: [Haskell-beginners] Profiling haskell code > I have just given it any random input array to be sorted. > The commands that I had sent earlier were tried on Cygwin... > ( > > > $ ghc --make Project.hs -prof -auto-all > > > > > > > > > $ Project +RTS -p > > > ) This ought to work fine. Just a note, to do any reasonable profiling you will need to give it a *much* larger list to sort. Otherwise it will execute so quickly that the timing data you get will be meaningless. > > Also can you tell me any other method for profiling the code that you > know? If you just want to see how long it takes to evaluate certain expressions, you can type ':set +s' in ghci; from then on after every expression you type it will tell you how long it took to evaluate and how much memory was used. -Brent From johanngiwer at web.de Fri Dec 5 06:14:07 2008 From: johanngiwer at web.de (Johann Giwer) Date: Fri Dec 5 06:07:57 2008 Subject: [Haskell-beginners] getRecursiveContents - example from `Real World Haskell' Message-ID: <20081205111405.GA18978@zitrone> `Real World Haskell' is a great book. I really love it. When I tried an example from the 9th Chapter, I was a bit disappointed: *Main> f <- getRecursiveContents "/home/johann/" Heap exhausted; Current maximum heap size is 128000000 bytes (122 Mb); use `+RTS -M' to increase it. The function lookes like this: getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do -- 1 let path = topdir name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return [path] return (concat paths) -- 2 OK, I'm using a small machine and my home directory contains ~30,000 files. But that couldn't be the real problem. And even if this function is a small example it should work reliable. The programming language I know best (and this is meant relative -- I'm only a `would be programmer') is python. Python has good support for functional programming, but no builtin tail recursion. So my first idea about the bug in `getRecursiveContents' went in this direction. Two hours later I had worked out this solution: getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents = getRecursiveContents' [] where getRecursiveContents' l p = E.handle (\_ -> return (p:l)) $ do -- 3 c <- getDirectoryContents p let c' = filter (`notElem` [".", ".."]) c x <- foldM (\l' p' -> getRecursiveContents' l' (p p')) l c' -- 4 return (x) Folding (4) and appending (3) would give less memory usage than mapping (1) and concatenation (2), I thought. This function worked well for small directory (for which the original one did, too). But tested with my home directory it went into an infinite loop. That led me to the actually problem: `doesDirectoryExist' also accepts symlinks to directories. Another hour later this was fixed: getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents = getRecursiveContents' [] where getRecursiveContents' l p = do s <- getSymbolicLinkStatus p if isDirectory s then E.handle (\_ -> return (p:l)) $ do c <- getDirectoryContents p let c' = filter (`notElem` [".", ".."]) c x <- foldM (\l' p' -> getRecursiveContents' l' (p p')) l c' return (x) else return (p:l) Finally I fixed the original function (this only took about 30 min :-). The handle (5) catches errors caused by unreadable directories getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = E.handle (\_ ->return [topdir]) $ do -- 5 names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir name s <- getSymbolicLinkStatus path if isDirectory s then getRecursiveContents path else return [path] return (concat paths) The imports for all functions mentioned above are: import Control.Monad ( forM, filterM, foldM ) import qualified Control.Exception as E import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath (()) import System.Posix (getSymbolicLinkStatus, isDirectory) Any suggestions about this solution are welcome. Johann From johanngiwer at web.de Fri Dec 5 07:07:57 2008 From: johanngiwer at web.de (Johann Giwer) Date: Fri Dec 5 07:01:47 2008 Subject: [Haskell-beginners] gtk2hs not rendering drawingArea In-Reply-To: References: Message-ID: <20081205120755.GA19194@zitrone> On Thu, Dec 04, 2008 at 01:07:06PM +0100, Norbert Wojtowicz wrote: > Hello, > > I'm having problems getting a drawingArea to render, I've narrowed the > program down to the following skeleton. Any suggestions on what I'm > doing wrong? The label gets updated correctly, but the drawingArea > just remains gray as if it was never rendered. I'm including an entire > compilable skeleton in case someone wants to help me debug it. (I have > a feeling I'm just missing something very obvious...) > > Thanks in advance, > Norbert > > skeletonTest.hs: > > module Main where > import Graphics.UI.Gtk -- hiding (fill) > import Graphics.UI.Gtk.Glade > import Graphics.Rendering.Cairo.SVG > import Graphics.Rendering.Cairo > import Control.Monad > > main = do > initGUI > let gFile = "brainSpin.glade" > windowXmlM <- xmlNew gFile > let windowXml = case windowXmlM of > (Just windowXml) -> windowXml > Nothing -> error "Can't find the glade file > \"brainSpin.glade\" in the current directory" > window <- xmlGetWidget windowXml castToWindow "brainSpinMain" > onDestroy window mainQuit > label <- xmlGetWidget windowXml castToLabel "label1" > drawArea <- xmlGetWidget windowXml castToDrawingArea "drawArea" > widgetShowAll window > labelSetText label "foo" > > -- THIS is the offending code. Originally I was working with SVGs, > but I simplified > -- it to this, just to track down the problem. It seems any Render () does not > -- get updated in the drawArea > let r = do setSourceRGB 0 0 0 > paint > drawin <- widgetGetDrawWindow drawArea > renderWithDrawable drawin r > > mainGUI Drawing must be done when the widget is exposed. The changes in the code below are mainly taken from demo/svg/SvgViewer.hs. main = do svg <- svgNewFromFile "/path/to/svg/file" let (width, height) = svgGetSize svg initGUI let gFile = "brainSpin.glade" windowXmlM <- xmlNew gFile let windowXml = case windowXmlM of (Just windowXml) -> windowXml Nothing -> error "Can't find the glade file \"brainSpin.glade\" in the current directory" window <- xmlGetWidget windowXml castToWindow "brainSpinMain" onDestroy window mainQuit label <- xmlGetWidget windowXml castToLabel "label1" drawArea <- xmlGetWidget windowXml castToDrawingArea "drawArea" -- Here we go onSizeRequest drawArea $ return (Requisition width height) onExpose drawArea $ updateCanvas drawArea svg widgetShowAll window labelSetText label "foo" mainGUI updateCanvas :: DrawingArea -> SVG -> Event -> IO Bool updateCanvas canvas svg (Expose { eventArea=rect }) = do drawin <- widgetGetDrawWindow canvas let (width, height) = svgGetSize svg (width', height') <- widgetGetSize canvas renderWithDrawable drawin $ do scale (realToFrac width' / realToFrac width) (realToFrac height' / realToFrac height) svgRender svg return True Hope, that's what you expected. -Johann From byorgey at seas.upenn.edu Fri Dec 5 08:24:26 2008 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Fri Dec 5 08:17:41 2008 Subject: [Haskell-beginners] Profiling haskell code In-Reply-To: <82C3BC9106BCE149B63464D79D0A22FD07C6AAED@sohm.kpit.com> References: <20081118121714.GA9052@seas.upenn.edu> <82C3BC9106BCE149B63464D79D0A22FD07C6AAED@sohm.kpit.com> Message-ID: <20081205132426.GA29651@seas.upenn.edu> To get the output of one function to be the input to another, you just apply one to the other. For example: -- This function generates a list foo :: Int -> [Int] foo n = [1..n] -- This function expects a list as input bar :: [Int] -> Int bar = sum . filter (>5) -- Use the output of foo as input to bar main = print $ bar (foo 20) Are you asking about something more than this? -Brent On Thu, Dec 04, 2008 at 05:42:42PM +0530, Sayali Kulkarni wrote: > Hey thanks Brent. This helped. > > I have one more question now. > > Consider I have two functions > 1. gives me a range of numbers in an array. > 2. has to get an array input for further process. > > Then how can I get the array generated by the first function tobe the > input of the second function? > > Regards, > Sayali > > -----Original Message----- > From: Brent Yorgey [mailto:byorgey@seas.upenn.edu] > Sent: Tuesday, November 18, 2008 5:47 PM > To: Sayali Kulkarni > Subject: Re: [Haskell-beginners] Profiling haskell code > > > I have just given it any random input array to be sorted. > > The commands that I had sent earlier were tried on Cygwin... > > ( > > > > $ ghc --make Project.hs -prof -auto-all > > > > > > > > > > > > $ Project +RTS -p > > > > ) > > This ought to work fine. Just a note, to do any reasonable profiling > you will need to give it a *much* larger list to sort. Otherwise it > will > execute so quickly that the timing data you get will be meaningless. > > > > > Also can you tell me any other method for profiling the code that you > > know? > > If you just want to see how long it takes to evaluate certain > expressions, you can type ':set +s' in ghci; from then on after every > expression you type it will tell you how long it took to evaluate and > how much memory was used. > > -Brent > From aleks_d at gmx.de Fri Dec 5 13:03:33 2008 From: aleks_d at gmx.de (=?utf-8?B?0JDQu9C10LrRgdCw0L3QtNGK0YAg0JsuINCU0LjQvNC40YLRgNC+0LI=?=) Date: Fri Dec 5 12:58:39 2008 Subject: [Haskell-beginners] Useful set of -W switches for .ghci? Message-ID: <20081205180333.GB30168@brmbr.sfs.uni-tuebingen.de> Hey list, I'm currently using :set -Wall in my .ghci to enforce some good coding practices on my side. Something like missing type signatures and the like. It has saved me quite a lot of hassle over the last couple of days as I experimented more with Haskell. But it seems, -Wall may be just a little too? overzealous: Prelude> 2^2 Warning: Defaulting the following constraint(s) to type `Integer' `Num t' arising from a use of `^' at :1:0-2 Warning: Defaulting the following constraint(s) to type `Integer' `Integral t' arising from a use of `^' at :1:0-2 Warning: Defaulting the following constraint(s) to type `Integer' `Num t' arising from a use of `^' at :1:0-2 Warning: Defaulting the following constraint(s) to type `Integer' `Integral t' arising from a use of `^' at :1:0-2 4 (I've shortened ghci's response a bit) So, do you have a good (recommended) set of -W switches for a newbie playing around in GHCi, so I can learn a good style? Forgive me if it's somewhere on page one of some book or tutorials - I've read so many of both, I'm beginning to forget things. Thanks, Aleks -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 197 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20081205/6b8ef7aa/attachment.bin From daniel.is.fischer at web.de Fri Dec 5 13:58:07 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Fri Dec 5 13:49:00 2008 Subject: [Haskell-beginners] Useful set of -W switches for .ghci? In-Reply-To: <20081205180333.GB30168@brmbr.sfs.uni-tuebingen.de> References: <20081205180333.GB30168@brmbr.sfs.uni-tuebingen.de> Message-ID: <200812051958.07980.daniel.is.fischer@web.de> Am Freitag, 5. Dezember 2008 19:03 schrieb ?????????? ?. ????????: > Hey list, > > I'm currently using :set -Wall in my .ghci to enforce some good coding > practices on my side. Something like missing type signatures and the like. > It has saved me quite a lot of hassle over the last couple of days as I > experimented more with Haskell. But it seems, -Wall may be just a little > too? overzealous: > > Prelude> 2^2 > > Warning: Defaulting the following constraint(s) to type `Integer' > `Num t' arising from a use of `^' at :1:0-2 > > Warning: Defaulting the following constraint(s) to type `Integer' > `Integral t' arising from a use of `^' at :1:0-2 > > Warning: Defaulting the following constraint(s) to type `Integer' > `Num t' arising from a use of `^' at :1:0-2 > > Warning: Defaulting the following constraint(s) to type `Integer' > `Integral t' arising from a use of `^' at :1:0-2 > 4 > > (I've shortened ghci's response a bit) > > So, do you have a good (recommended) set of -W switches for a newbie > playing around in GHCi, so I can learn a good style? Forgive me if it's > somewhere on page one of some book or tutorials - I've read so many of > both, I'm beginning to forget things. > Turn off those warnings you don't want, like $ ghci -Wall -fno-warn-type-defaults GHCi, version 6.8.3: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. Prelude> 2^2 4 A list of warning options is in section 5.7 of the user's guide (unless it's moved in the 6.10 branch). > Thanks, > Aleks Cheers, Daniel From aleks_d at gmx.de Fri Dec 5 18:06:50 2008 From: aleks_d at gmx.de (=?utf-8?B?0JDQu9C10LrRgdCw0L3QtNGK0YAg0JsuINCU0LjQvNC40YLRgNC+0LI=?=) Date: Fri Dec 5 18:01:48 2008 Subject: [Haskell-beginners] Useful set of -W switches for .ghci? In-Reply-To: <200812051958.07980.daniel.is.fischer@web.de> References: <20081205180333.GB30168@brmbr.sfs.uni-tuebingen.de> <200812051958.07980.daniel.is.fischer@web.de> Message-ID: <20081205230650.GA23447@brmbr.sfs.uni-tuebingen.de> Also Sprach Daniel Fischer: > Turn off those warnings you don't want, like > > $ ghci -Wall -fno-warn-type-defaults > GHCi, version 6.8.3: http://www.haskell.org/ghc/ :? for help > Loading package base ... linking ... done. > Prelude> 2^2 > 4 > > A list of warning options is in section 5.7 of the user's guide (unless it's > moved in the 6.10 branch). Thanks very much, the location seems to be the same, Aleks -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 197 bytes Desc: not available Url : http://www.haskell.org/pipermail/beginners/attachments/20081206/141af60b/attachment-0001.bin From wojtowicz.norbert at gmail.com Sat Dec 6 06:58:30 2008 From: wojtowicz.norbert at gmail.com (Norbert Wojtowicz) Date: Sat Dec 6 06:51:42 2008 Subject: [Haskell-beginners] gtk2hs not rendering drawingArea In-Reply-To: <20081205120755.GA19194@zitrone> References: <20081205120755.GA19194@zitrone> Message-ID: Thanks Johann! That explains what I was doing wrong. For my purposes, I switched over to the onExposeRect, but the same idea still holds. Thanks for pointing me in the right direction. From littlesweetmelon at gmail.com Mon Dec 8 07:40:16 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Mon Dec 8 07:33:22 2008 Subject: [Haskell-beginners] [haskell] About CPS form funtions Message-ID: Hi, I am confused by section 4.6 in Yet Another Haskell Tutorial written by Hal Daume III. The auther provides a CPS form of "fold" funtion, but I don't know: 1. How to transform a normal function into CPS function. I need some hint in writting "cfold". 2. Why "cfold" is CPS form? In my mind, if a CPS funtion calls to other CPS function, it must only feed that function with either direct variables or continuations. But in the tutorial, cfold defines: cfold f z l = cfold' (\x t g -> f x (g t)) z l Note that the lambda function body is f x (g t); which means call g(t) first, and take the result, then call f(x, r). It is illegal in CPS because g(t) will never return. This is not same with function f. Here, f can be treated as atomic operation (belong the CPS system). Anyone can help me? Thank you in advance. --- melon From 666wman at gmail.com Mon Dec 8 10:38:01 2008 From: 666wman at gmail.com (wman) Date: Mon Dec 8 10:31:07 2008 Subject: [Haskell-beginners] [haskell] About CPS form funtions In-Reply-To: References: Message-ID: On Mon, Dec 8, 2008 at 1:40 PM, ?? wrote: > Hi, > I am confused by section 4.6 in Yet Another Haskell Tutorial written > by Hal Daume III. > The auther provides a CPS form of "fold" funtion, but I don't know: > 1. How to transform a normal function into CPS function. I need some > hint in writting "cfold". Normal function(s) return value(s). CPS functions take the same value and uses/throws it as a parameter/argument to the "extra" argument, the Continuation. so to transform a function into CPS just 1) make the function take one extra argument, the continuation (the "rest" of the process, next function in chain) 2) instead of returning a value, apply the continuation to the value (call the continuation with the result you would normally return) Example (taken from http://en.wikibooks.org/wiki/Haskell/CPS , check it out) square :: Int -> Int square x = x ^ 2 main = do let x = square 4 print x in CPS : squareCPS :: Int -> (Int -> a) -> a squareCPS x k = k (x ^ 2) main = squareCPS 4 print which shows that here, the print function is the continuation for the square function. instead of returning the value (16, or 4*4 here), the CPS variant feeds the value to the continuation (print here) hope it helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081208/448b7174/attachment.htm From byorgey at seas.upenn.edu Mon Dec 8 12:21:47 2008 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Mon Dec 8 12:14:54 2008 Subject: [Haskell-beginners] Profiling haskell code In-Reply-To: <82C3BC9106BCE149B63464D79D0A22FD07CCC49B@sohm.kpit.com> References: <20081205132426.GA29651@seas.upenn.edu> <82C3BC9106BCE149B63464D79D0A22FD07CCC49B@sohm.kpit.com> Message-ID: <20081208172147.GA15924@seas.upenn.edu> > --function "number" which generates an array of numbers, it takes the > ends of the range for numbers as inputs > > number s e = if s > e > then [] > else s : number (s + 1) e Just an aside: instead of 'number s e' you can just write [s..e] . > Now I want the array of numbers generated by the first function "number" > tobe the input of the second function"quicksort". > Then how should I apply the function number to quicksort? Like this: quicksort (number 3 50) You always apply a function f to an input x like this: f x . So the above code says to apply quicksort to the input (number 3 50), which is of course the output from applying number to the inputs 3 and 50. The parentheses are needed since without them, 'quicksort number 3 50' tries to give three inputs to quicksort, namely 'number' '3' and '50', which is obviously wrong. > Also do tel me which is the book that I can refer to for Haskell? There are many available books and online tutorials. Some ones I might recommend for you: The Haskell wikibook -- http://en.wikibooks.org/wiki/Haskell Yet Another Haskell Tutorial -- http://en.wikibooks.org/wiki/Haskell/YAHT Learn You a Haskell -- www.learnyouahaskell.com Programming in Haskell -- http://www.amazon.com/Programming-Haskell-Graham-Hutton/dp/0521692695 There are many other books and tutorials as well -- e.g., the Gentle Introduction to Haskell, the Haskell School of Expression, and Real World Haskell (just google them if you are interested). Check these out and hopefully you can find something that you like. -Brent > > > Regards, > Sayali. > > -----Original Message----- > From: beginners-bounces@haskell.org > [mailto:beginners-bounces@haskell.org] On Behalf Of Brent Yorgey > Sent: Friday, December 05, 2008 6:54 PM > To: beginners@haskell.org > Subject: Re: [Haskell-beginners] Profiling haskell code > > To get the output of one function to be the input to another, you just > apply one to the other. For example: > > -- This function generates a list > foo :: Int -> [Int] > foo n = [1..n] > > -- This function expects a list as input > bar :: [Int] -> Int > bar = sum . filter (>5) > > -- Use the output of foo as input to bar > main = print $ bar (foo 20) > > Are you asking about something more than this? > > -Brent > > On Thu, Dec 04, 2008 at 05:42:42PM +0530, Sayali Kulkarni wrote: > > Hey thanks Brent. This helped. > > > > I have one more question now. > > > > Consider I have two functions > > 1. gives me a range of numbers in an array. > > 2. has to get an array input for further process. > > > > Then how can I get the array generated by the first function tobe the > > input of the second function? > > > > Regards, > > Sayali > > > > -----Original Message----- > > From: Brent Yorgey [mailto:byorgey@seas.upenn.edu] > > Sent: Tuesday, November 18, 2008 5:47 PM > > To: Sayali Kulkarni > > Subject: Re: [Haskell-beginners] Profiling haskell code > > > > > I have just given it any random input array to be sorted. > > > The commands that I had sent earlier were tried on Cygwin... > > > ( > > > > > $ ghc --make Project.hs -prof -auto-all > > > > > > > > > > > > > > > $ Project +RTS -p > > > > > ) > > > > This ought to work fine. Just a note, to do any reasonable profiling > > you will need to give it a *much* larger list to sort. Otherwise it > > will > > execute so quickly that the timing data you get will be meaningless. > > > > > > > > Also can you tell me any other method for profiling the code that > you > > > know? > > > > If you just want to see how long it takes to evaluate certain > > expressions, you can type ':set +s' in ghci; from then on after every > > expression you type it will tell you how long it took to evaluate and > > how much memory was used. > > > > -Brent > > > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners > From Sayali.Kulkarni at kpitcummins.com Sun Dec 7 23:58:24 2008 From: Sayali.Kulkarni at kpitcummins.com (Sayali Kulkarni) Date: Mon Dec 8 21:49:57 2008 Subject: [Haskell-beginners] Profiling haskell code In-Reply-To: <20081205132426.GA29651@seas.upenn.edu> Message-ID: <82C3BC9106BCE149B63464D79D0A22FD07CCC49B@sohm.kpit.com> Hello Brent , Thanks for the solution.... Now I have the 2 functions called number and quicksort resp. as follows: --function "number" which generates an array of numbers, it takes the ends of the range for numbers as inputs number s e = if s > e then [] else s : number (s + 1) e -- this is the same quicksort function that I had used before quicksort [] = [] quicksort (x : xs) = quicksort larger ++ [x ] ++ quicksort smaller where smaller = [a | a <- xs, a <= x ] larger = [b | b <- xs, b > x ] Now I want the array of numbers generated by the first function "number" tobe the input of the second function"quicksort". Then how should I apply the function number to quicksort? Can you help me out with this? Also do tel me which is the book that I can refer to for Haskell? Regards, Sayali. -----Original Message----- From: beginners-bounces@haskell.org [mailto:beginners-bounces@haskell.org] On Behalf Of Brent Yorgey Sent: Friday, December 05, 2008 6:54 PM To: beginners@haskell.org Subject: Re: [Haskell-beginners] Profiling haskell code To get the output of one function to be the input to another, you just apply one to the other. For example: -- This function generates a list foo :: Int -> [Int] foo n = [1..n] -- This function expects a list as input bar :: [Int] -> Int bar = sum . filter (>5) -- Use the output of foo as input to bar main = print $ bar (foo 20) Are you asking about something more than this? -Brent On Thu, Dec 04, 2008 at 05:42:42PM +0530, Sayali Kulkarni wrote: > Hey thanks Brent. This helped. > > I have one more question now. > > Consider I have two functions > 1. gives me a range of numbers in an array. > 2. has to get an array input for further process. > > Then how can I get the array generated by the first function tobe the > input of the second function? > > Regards, > Sayali > > -----Original Message----- > From: Brent Yorgey [mailto:byorgey@seas.upenn.edu] > Sent: Tuesday, November 18, 2008 5:47 PM > To: Sayali Kulkarni > Subject: Re: [Haskell-beginners] Profiling haskell code > > > I have just given it any random input array to be sorted. > > The commands that I had sent earlier were tried on Cygwin... > > ( > > > > $ ghc --make Project.hs -prof -auto-all > > > > > > > > > > > > $ Project +RTS -p > > > > ) > > This ought to work fine. Just a note, to do any reasonable profiling > you will need to give it a *much* larger list to sort. Otherwise it > will > execute so quickly that the timing data you get will be meaningless. > > > > > Also can you tell me any other method for profiling the code that you > > know? > > If you just want to see how long it takes to evaluate certain > expressions, you can type ':set +s' in ghci; from then on after every > expression you type it will tell you how long it took to evaluate and > how much memory was used. > > -Brent > _______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners From moritz.tacke at gmail.com Mon Dec 8 11:55:56 2008 From: moritz.tacke at gmail.com (Moritz Tacke) Date: Mon Dec 8 21:50:14 2008 Subject: [Haskell-beginners] HDBC commit problem Message-ID: <814cf9120812080855t6062d05by481e4e48ca4780a2@mail.gmail.com> Hi! I am running into problems while using HDBC with the sqlite3 backend. The HDBC "commit" statement frequently results in exceptions with the sqlite3 errorcode 1, "SQL logic error or no database". As far as I know, and as far as the HDBC docs tell me, "commit" simply writes all yet open transactions onto the disk. How can it fail? The HDBC documetation mentions the prepare- and execute-steps as the ones which might throw exceptions - what are the problems a call to "commit" might encounter? I do not suspect SQL errors to be the cause - those should lead to earlier exceptions - and the database is definitly present and opened, as select calls following the failing commit statments succeed. Greetings! From artyom.shalkhakov at gmail.com Tue Dec 9 06:30:28 2008 From: artyom.shalkhakov at gmail.com (Artyom Shalkhakov) Date: Tue Dec 9 06:23:31 2008 Subject: [Haskell-beginners] Bit arithmetic in Haskell Message-ID: <2076f2f90812090330p49bd5e15q801aee1079eba81b@mail.gmail.com> Hello, I'm trying to do some bit arithmetic. Here's the function: > import Data.Bits > import Data.Word > > g :: Word32 -> [Word32] > g x = [(x `shiftR` 24) .&. 0xFF, > (x `shiftR` 16) .&. 0xFF, > (x `shiftR` 8) .&. 0xFF, > x .&. 0xFF] This function should give bytes for the given number, like this: g 255 -> [0,0,0,255] g 256 -> [0,0,1,255] g 65535 -> [0,0,255,255] In reality, I get very strange answers. Can anybody help me please? Regards, Artyom Shalkhakov. From byorgey at seas.upenn.edu Tue Dec 9 08:02:46 2008 From: byorgey at seas.upenn.edu (Brent Yorgey) Date: Tue Dec 9 07:55:48 2008 Subject: [Haskell-beginners] Bit arithmetic in Haskell In-Reply-To: <2076f2f90812090330p49bd5e15q801aee1079eba81b@mail.gmail.com> References: <2076f2f90812090330p49bd5e15q801aee1079eba81b@mail.gmail.com> Message-ID: <20081209130246.GA20710@seas.upenn.edu> On Tue, Dec 09, 2008 at 05:30:28PM +0600, Artyom Shalkhakov wrote: > Hello, > > I'm trying to do some bit arithmetic. Here's the function: > > > import Data.Bits > > import Data.Word > > > > g :: Word32 -> [Word32] > > g x = [(x `shiftR` 24) .&. 0xFF, > > (x `shiftR` 16) .&. 0xFF, > > (x `shiftR` 8) .&. 0xFF, > > x .&. 0xFF] > > This function should give bytes for the given number, like this: > > g 255 -> [0,0,0,255] This is the answer I get when I evaluate (g 255). > g 256 -> [0,0,1,255] This is incorrect -- the bytes for 256 are [0,0,1,0], which is correctly computed by g. [0,0,1,255] would be 1*256 + 255 = 511, and giving 511 as input to g indeed results in [0,0,1,255]. > g 65535 -> [0,0,255,255] When I evaluate (g 65535) this is what I get, too. In short, it seems to me that g works perfectly. If it doesn't work for you, can you give specific examples of the output it should give, and the output you get instead? -Brent From take at informatik.uni-freiburg.de Tue Dec 9 08:58:14 2008 From: take at informatik.uni-freiburg.de (Moritz Tacke) Date: Tue Dec 9 08:51:16 2008 Subject: [Haskell-beginners] HDBC commit problem In-Reply-To: <814cf9120812080855t6062d05by481e4e48ca4780a2@mail.gmail.com> References: <814cf9120812080855t6062d05by481e4e48ca4780a2@mail.gmail.com> Message-ID: <814cf9120812090558k42814eeaye9914e16abec2961@mail.gmail.com> Hi! I am running into problems while using HDBC with the sqlite3 backend. The HDBC "commit" statement frequently results in exceptions with the sqlite3 error code 1, "SQL logic error or no database". As far as I know, and as far as the HDBC docs tell me, "commit" simply writes all yet open transactions onto the disk. How can it fail? Given the implicit opening of transactions as done by HDBC, a call to commit should succeed in any situation (or am I wrong?). The HDBC documentation mentions the prepare- and execute-steps as the ones which might throw exceptions - what are the problems a call to "commit" might encounter? I do not suspect SQL errors to be the cause - those should lead to earlier exceptions - and the database is definitly present and opened, as select calls following the failing commit statments succeed. Greetings! From t-otto-news at gmx.de Tue Dec 9 09:35:01 2008 From: t-otto-news at gmx.de (Torsten Otto) Date: Tue Dec 9 09:28:08 2008 Subject: [Haskell-beginners] Wrapping random In-Reply-To: <20081129170223.GD25356@localhost.localdomain> References: <20081129170223.GD25356@localhost.localdomain> Message-ID: <327D1C4E-B1FF-44EC-BCB0-7DDA5BCE5CA2@gmx.de> Thanks a bunch for the replies, they were much appreciated. In the meantime we talked in more depth than I had initially planned to about randomness, statefulness and even monads to some extent. (And the chatbot gives its random replies as was planned :-) ) Kind regards, Torsten From artyom.shalkhakov at gmail.com Tue Dec 9 23:02:02 2008 From: artyom.shalkhakov at gmail.com (Artyom Shalkhakov) Date: Tue Dec 9 22:55:04 2008 Subject: [Haskell-beginners] Re: Bit arithmetic in Haskell In-Reply-To: <2076f2f90812090330p49bd5e15q801aee1079eba81b@mail.gmail.com> References: <2076f2f90812090330p49bd5e15q801aee1079eba81b@mail.gmail.com> Message-ID: <2076f2f90812092002u4db622abmfa67edb989200fe8@mail.gmail.com> Hello, It looks like I have some problems with math. Problem solved. Regards, Artyom Shalkhakov. From levi.stephen at gmail.com Sun Dec 14 18:11:29 2008 From: levi.stephen at gmail.com (Levi Stephen) Date: Sun Dec 14 18:04:15 2008 Subject: [Haskell-beginners] A type level programming question Message-ID: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> Hi, I was looking at Data.Param.FSVec from parameterized-data [1]. The method to retrieve an element from a FSVec has the following type: (!) :: (Pos s, Nat i, i :<: s) => FSVec s a -> i -> a I was wondering if it was possible to write a function of type: elementAt :: FSVec s a -> Int -> a that called the above function, throwing an error if the index was out of bounds. e.g., elementAt v idx | idx < 0 || idx > length v = error "Out of bounds" | otherwise = .... But, I can't figure out how to implement the otherwise part. In particular I can't work out how to call the (!) function with the i :<: s class constraint satisfied. Thanks, Levi From 666wman at gmail.com Mon Dec 15 05:35:24 2008 From: 666wman at gmail.com (wman) Date: Mon Dec 15 05:28:08 2008 Subject: [Haskell-beginners] Re: [Haskell] Re: Help : A problem with IO In-Reply-To: <719881900811271010r313d3becqefa9fa4b772b5666@mail.gmail.com> References: <719881900811260812p207fcbb2y9ad6d1f33a13ed10@mail.gmail.com> <719881900811260818n5899ab93v51b509cd38dba166@mail.gmail.com> <719881900811271010r313d3becqefa9fa4b772b5666@mail.gmail.com> Message-ID: you probably got it pointed out in haskell-beginners, but in case not: On Thu, Nov 27, 2008 at 7:10 PM, abdullah abdul Khadir < abdullah.ak2002@gmail.com> wrote: > a) I need to put a do after else for more than one instruction (?) No, the do thingy is a syntactic sugar for chaining "warm, fuzzy" (the "preffered" wannabe-joke-term for the presumably scary term monads/monadic) operations. it allows you to write in "classical" imperative/sequential style instead of chaining operations manually (using the >> and >>= operators, which the do notation translates into anyway). lookup some monad tutorials/docs. you are right in that if there is only one operation, no transformation is needed, so the do is unnecessary. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081215/cb2fd47b/attachment.htm From michael at snoyman.com Mon Dec 15 12:49:38 2008 From: michael at snoyman.com (Michael Snoyman) Date: Mon Dec 15 12:44:25 2008 Subject: [Haskell-beginners] Existential data types Message-ID: <29bf512f0812150949w237cec4arb7e7dc92b88968d7@mail.gmail.com> Hi everyone, I believe I have come to the conclusion that what I would like to do is impossible, but I would like to have that confirmed. I would basically like to be able to have a heterogeneous list without boxing everything in a data type. Below is the sample code, with the code I would like to use commented out. I'm I missing something, or does Haskell simply not support what I am trying for? {-# LANGUAGE ExistentialQuantification #-} data Foo = Foo String class IFoo a where toFoo :: a -> Foo instance IFoo Foo where toFoo = id data A = A String instance IFoo A where toFoo (A a) = Foo a data B = B Int instance IFoo B where toFoo (B b) = Foo $ show b data FooBox = forall t. IFoo t => FooBox t instance IFoo FooBox where toFoo (FooBox f) = toFoo f myPrint :: IFoo t => [(String, t)] -> IO () myPrint = mapM_ myPrint' myPrint' :: IFoo t => (String, t) -> IO () myPrint' (key, value) = let (Foo foo) = toFoo value in putStrLn $ key ++ ": " ++ foo {- What I'd like to do: main = myPrint [ ("one", Foo "1") , ("two", A "2") ] -} main = myPrint [ ("one", FooBox $ Foo "1") , ("two", FooBox $ A "2") ] ---- Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081215/05e6c5ee/attachment.htm From wojtowicz.norbert at gmail.com Mon Dec 15 14:02:31 2008 From: wojtowicz.norbert at gmail.com (Norbert Wojtowicz) Date: Mon Dec 15 13:55:14 2008 Subject: [Haskell-beginners] gtk2hs timeoutSeq Message-ID: Hello, I'm trying to use a sequence of timeoutAdd's in a gtk2hs app. By sequence, I mean one (IO Bool) must return as False before the next begins: timeoutSeq [ (fn1, 100), (fn2, 200) ] fn1 will keep running every 100, until it returns False. Then fn2 will get a timeoutAdd 200, and so on... First attempt (works fine, I think): timeoutSeq :: [(IO Bool, Int)] -> IO () timeoutSeq [] = return () timeoutSeq ((fn,n):rest) = do timeoutAdd (aux fn rest) n return () where aux :: IO Bool -> [(IO Bool, Int)] -> IO Bool aux fn [] = fn aux fn lst = do r <- fn case r of True -> return True False -> do timeoutSeq lst return False Now, I'd like to write a timeoutDep (fn1, n1) (fn2, n2) where fn1 and fn2 are both running at their respective rates, and fn1 will run only as long as fn2 is running. The use case for this is eg: Run fn1 often and fn2 less often, but I only care fn1 to be running as long as fn2 is still valid. timeoutDep (fn,n) (fn2,n2) = do hdl <- timeoutAdd fn n timeoutSeq [(aux fn2 hdl, n2), (return False, 100)] where aux fn2 hdl = do r <- fn2 case r of True -> return True False -> do timeoutRemove hdl return False This implementation sort of works, except it exits immiediately (and as IO ()), so I can't for example do this: timeoutSeq [((timeoutDep (print "a" >> return True, 100) (print "b" >> return True, 100)), 100) , (print "c" >> return False, 100)] Ths silly example should keep printing 'a' and 'b' w/o ever printing 'c'. Any ideas or suggestions? From allbery at ece.cmu.edu Mon Dec 15 14:55:35 2008 From: allbery at ece.cmu.edu (Brandon S. Allbery KF8NH) Date: Mon Dec 15 14:48:25 2008 Subject: [Haskell-beginners] Existential data types In-Reply-To: <29bf512f0812150949w237cec4arb7e7dc92b88968d7@mail.gmail.com> References: <29bf512f0812150949w237cec4arb7e7dc92b88968d7@mail.gmail.com> Message-ID: <82658DA2-D2B7-4A26-9F97-933E2C4C65C5@ece.cmu.edu> On 2008 Dec 15, at 12:49, Michael Snoyman wrote: > I believe I have come to the conclusion that what I would like to do > is impossible, but I would like to have that confirmed. I would > basically like to be able to have a heterogeneous list without > boxing everything in a data type. Below is the sample code, with the > code I would like to use commented out. I'm I missing something, or > does Haskell simply not support what I am trying for? It's possible but nontrivial. Look at HList on http://hackage.haskell.org for an implementation. -- 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 -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081215/3468c257/attachment-0001.htm From jgbailey at gmail.com Mon Dec 15 15:03:55 2008 From: jgbailey at gmail.com (Justin Bailey) Date: Mon Dec 15 14:56:41 2008 Subject: [Haskell-beginners] A type level programming question In-Reply-To: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> References: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> Message-ID: On Sun, Dec 14, 2008 at 3:11 PM, Levi Stephen wrote: > (!) :: (Pos s, Nat i, i :<: s) => FSVec s a -> i -> a > > I was wondering if it was possible to write a function of type: > > elementAt :: FSVec s a -> Int -> a > > that called the above function, throwing an error if the index was out > of bounds. e.g., > Why would you want to write that function? From the signature on (!), it looks like any out of bounds errors should occur at compile time. I'd say the library is trying to make it so you don't have to write that function. That said, I'd try removing the type signature from elementAt and see what your compiler infers for you. You'll also have to find a way to relate "idx" to "v". Unless "length v" returns a Nat, the comparison you have won't do it. Justin From jcb at iteris.com Mon Dec 15 15:17:33 2008 From: jcb at iteris.com (Jeff C. Britton) Date: Mon Dec 15 15:10:20 2008 Subject: [Haskell-beginners] Problems with one of my first examples Message-ID: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> Hello, I have started reading "Yet Another Haskell Tutorial" by Hal Daum?e III which can be found here http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf One of the early examples in section 3.8 pg. 35 is this askForWords = do putStrLn "Please enter a word:" word <- getLine if word == "" then return [] else do rest <- askForWords return (word : rest) I want to print the returned list and everything I try fails. I have tried the following: printList l = if length l >= 1 then do putStrLn (head l) printList (tail l) else putStrLn("") f = printList askForWords and I get Expression : printList askForWords *** Term : askForWords *** Type : IO [[Char]] *** Does not match : [[Char]] ************************************* The exercise right below this asks for a very slight modification to read numbers instead. However, I am confused about how to convert strings to numbers. If I type in the hugs interactive console read "5" + 3 --> 8 -- ok perfect However read "5" gives ERROR - Unresolved overloading *** Type : Read a => a *** Expression : read "5" Yet page 33 of the tutorial has the following code: doGuessing num = do putStrLn "Enter your guess:" guess <- getLine let guessNum = read guess -- ok in let stmt, but not at repl prompt? Anyway I take the info that has been presented and create this function: askForNumbers = do hSetBuffering stdin LineBuffering putStrLn "Give me a number (or 0 to stop)" numStr <- getLine let num = read numStr if num == 0 then return [] else do rest <- askForNumbers return (num : rest) However, when I try to use it, like say map sqrt askForNumbers ERROR - Type error in application *** Expression : map sqrt askForNumbers *** Term : askForNumbers *** Type : IO [Integer] *** Does not match : [a] ********************************************************* Is there a way to write printList to handle Strings or numbers? Or should I write printList (map show askForNumbers) Thanks, Jeff ? From michael at snoyman.com Mon Dec 15 15:48:16 2008 From: michael at snoyman.com (Michael Snoyman) Date: Mon Dec 15 15:42:28 2008 Subject: [Haskell-beginners] Problems with one of my first examples In-Reply-To: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> References: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> Message-ID: <29bf512f0812151248p163b3101pb9fe83c63685f1bd@mail.gmail.com> On Mon, Dec 15, 2008 at 12:17 PM, Jeff C. Britton wrote: > Hello, > > I have started reading "Yet Another Haskell Tutorial" by Hal Daum?e III > which can be found here > http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf > > One of the early examples in section 3.8 pg. 35 > is this > > askForWords = do > putStrLn "Please enter a word:" > word <- getLine > if word == "" > then return [] > else do > rest <- askForWords > return (word : rest) > > I want to print the returned list and everything I try fails. > > I have tried the following: > > printList l = > if length l >= 1 > then do putStrLn (head l) > printList (tail l) > else putStrLn("") > > f = printList askForWords > > and I get > Expression : printList askForWords > *** Term : askForWords > *** Type : IO [[Char]] > *** Does not match : [[Char]] I believe one of the following will work for you: f = askForWords >>= printList f = do words <- askForWords printList words > > > > ************************************* > The exercise right below this asks for a very slight modification to read > numbers instead. > > However, I am confused about how to convert strings to numbers. > If I type in the hugs interactive console > read "5" + 3 --> 8 -- ok perfect > > However > read "5" gives > ERROR - Unresolved overloading > *** Type : Read a => a > *** Expression : read "5" > > Yet page 33 of the tutorial has the following code: > doGuessing num = do > putStrLn "Enter your guess:" > guess <- getLine > let guessNum = read guess -- ok in let stmt, but not at repl prompt? The problem here is type inference. The statement read "5" has type "(Read a) => a", which basically means anything that implements the class "Read." When you do read "5" + 3, the read "5" gets the type of the 3. I assume that in the latter case, you use the expression guessNum in a way later on that the compiler can infer its type. > > > > Anyway I take the info that has been presented and create this function: > askForNumbers = do > hSetBuffering stdin LineBuffering > putStrLn "Give me a number (or 0 to stop)" > numStr <- getLine > let num = read numStr > if num == 0 > then return [] > else do > rest <- askForNumbers > return (num : rest) > > However, when I try to use it, like say > > map sqrt askForNumbers > > ERROR - Type error in application > *** Expression : map sqrt askForNumbers > *** Term : askForNumbers > *** Type : IO [Integer] > *** Does not match : [a] Similar to above, try this: do nums <- askForNumbers map sqrt nums > > > ********************************************************* > > Is there a way to write printList to handle Strings or numbers? > Or should I write > printList (map show askForNumbers) Note: you should probably do this using mapM_, but for simplicity, I'll do it using explicit recursion: printList [] = putStrLn "" -- or return () if you don't want the extra blank line printList (x:xs) = do putStrLn (show x) printList xs If you have any questions about how these worked, let me know! Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081215/03bfa53c/attachment.htm From levi.stephen at gmail.com Mon Dec 15 17:06:09 2008 From: levi.stephen at gmail.com (Levi Stephen) Date: Mon Dec 15 17:00:01 2008 Subject: [Haskell-beginners] A type level programming question In-Reply-To: References: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> Message-ID: <8341e4f40812151406p101192aal97c6a9becf4f3bb9@mail.gmail.com> On Tue, Dec 16, 2008 at 6:33 AM, Justin Bailey wrote: > On Sun, Dec 14, 2008 at 3:11 PM, Levi Stephen wrote: >> (!) :: (Pos s, Nat i, i :<: s) => FSVec s a -> i -> a >> >> I was wondering if it was possible to write a function of type: >> >> elementAt :: FSVec s a -> Int -> a >> >> that called the above function, throwing an error if the index was out >> of bounds. e.g., >> > > Why would you want to write that function? From the signature on (!), > it looks like any out of bounds errors should occur at compile time. > I'd say the library is trying to make it so you don't have to write > that function. I may not have to write this function, but I'm guessing at some stage it's going to be necessary to convert from value level integers to type level. Is this a bad guess? The type-level library provides the function reifyIntegral for this purpose, but the continuation is only allowed to rely on the Nat class constraint. > > That said, I'd try removing the type signature from elementAt and see > what your compiler infers for you. I don't know how to implement elementAt yet. FSVec provides the (!) function for accessing elements, but I need to satisfy the i :<: s class constraint before calling it. > You'll also have to find a way to > relate "idx" to "v". Unless "length v" returns a Nat, the comparison > you have won't do it. length has type forall s a. Nat s => FSVec s a -> Int > > Justin > Thanks, Levi From jcb at iteris.com Mon Dec 15 17:26:11 2008 From: jcb at iteris.com (Jeff C. Britton) Date: Mon Dec 15 17:18:54 2008 Subject: [Haskell-beginners] Problems with one of my first examples In-Reply-To: <29bf512f0812151248p163b3101pb9fe83c63685f1bd@mail.gmail.com> References: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> <29bf512f0812151248p163b3101pb9fe83c63685f1bd@mail.gmail.com> Message-ID: <10776152C3DA8244BAA5D5B10853FE99044E7A28@BULLDOG.iteris.com> Thanks, Michael. Ok, I understand most of what you did, but ... do nums <- askForNumbers; map sqrt nums ERROR - Type error in final generator *** Term : map sqrt nums *** Type : [Integer] *** Does not match : IO a do nums <- askForNumbers; printList nums -- works fine Thanks, Jeff ------------------------------------------------------------- Hello, I have started reading "Yet Another Haskell Tutorial" by Hal Daum?e III which can be found here http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf One of the early examples in section 3.8 pg. 35 is this askForWords = do ?putStrLn "Please enter a word:" ?word <- getLine ?if word == "" ? ?then return [] ? ?else do ? ? ?rest <- askForWords ? ? ?return (word : rest) I want to print the returned list and everything I try fails. I have tried the following: printList l = ?if length l >= 1 ? ?then do putStrLn (head l) ? ? ? ? ? ?printList (tail l) ? ?else putStrLn("") f = printList askForWords and I get Expression ? ? : printList askForWords *** Term ? ? ? ? ? : askForWords *** Type ? ? ? ? ? : IO [[Char]] *** Does not match : [[Char]] I believe one of the following will work for you: f = askForWords >>= printList f = do ? ? ? ? words <- askForWords ? ? ? ? printList words ? ************************************* The exercise right below this asks for a very slight modification to read numbers instead. However, I am confused about how to convert strings to numbers. If I type in the hugs interactive console read "5" + 3 --> 8 ? ? -- ok perfect However read "5" gives ERROR - Unresolved overloading *** Type ? ? ? : Read a => a *** Expression : read "5" Yet page 33 of the tutorial has the following code: doGuessing num = do ?putStrLn "Enter your guess:" ?guess <- getLine ?let guessNum = read guess ?-- ok in let stmt, but not at repl prompt? The problem here is type inference. The statement read "5" has type "(Read a) => a", which basically means anything that implements the class "Read." When you do read "5" + 3, the read "5" gets the type of the 3. I assume that in the latter case, you use the expression guessNum in a way later on that the compiler can infer its type. Anyway I take the info that has been presented and create this function: askForNumbers = do ? ?hSetBuffering stdin LineBuffering ? ?putStrLn "Give me a number (or 0 to stop)" ? ?numStr <- getLine ? ?let num = read numStr ? ?if num == 0 ? ? ? ?then return [] ? ? ? ?else do ? ? ? ? ? ?rest <- askForNumbers ? ? ? ? ? ?return (num : rest) However, when I try to use it, like say map sqrt askForNumbers ERROR - Type error in application *** Expression ? ? : map sqrt askForNumbers *** Term ? ? ? ? ? : askForNumbers *** Type ? ? ? ? ? : IO [Integer] *** Does not match : [a] Similar to above, try this: do nums <- askForNumbers ? ? map sqrt nums ? ********************************************************* Is there a way to write printList to handle Strings or numbers? Or should I write printList (map show askForNumbers) Note: you should probably do this using mapM_, but for simplicity, I'll do it using explicit recursion: printList [] = putStrLn "" -- or return () if you don't want the extra blank line printList (x:xs) = do putStrLn (show x) ????????????????????? printList xs If you have any questions about how these worked, let me know! Michael From daniel.is.fischer at web.de Mon Dec 15 17:40:59 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 15 17:31:15 2008 Subject: [Haskell-beginners] Problems with one of my first examples In-Reply-To: <10776152C3DA8244BAA5D5B10853FE99044E7A28@BULLDOG.iteris.com> References: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> <29bf512f0812151248p163b3101pb9fe83c63685f1bd@mail.gmail.com> <10776152C3DA8244BAA5D5B10853FE99044E7A28@BULLDOG.iteris.com> Message-ID: <200812152340.59456.daniel.is.fischer@web.de> Am Montag, 15. Dezember 2008 23:26 schrieb Jeff C. Britton: > Thanks, Michael. > > Ok, I understand most of what you did, but ... > > do nums <- askForNumbers; map sqrt nums > > ERROR - Type error in final generator > *** Term : map sqrt nums > *** Type : [Integer] > *** Does not match : IO a There's another one lurking there, :t sqrt sqrt :: (Floating a) => a -> a but Integer is not a member of class Floating. The one displayed says that you must have an IO-action in your do-block, not a plain list of numbers. do nums <- askForNumbers printList $ map (sqrt . fromInteger) nums works, or printList . map (sqrt . fromInteger) =<< askForNumbers > > do nums <- askForNumbers; printList nums -- works fine > > Thanks, > > Jeff > > > ------------------------------------------------------------- > Hello, > > I have started reading "Yet Another Haskell Tutorial" by Hal Daum?e III > which can be found here http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf > > One of the early examples in section 3.8 pg. 35 > is this > > askForWords = do > putStrLn "Please enter a word:" > word <- getLine > if word == "" > then return [] > else do > rest <- askForWords > return (word : rest) > > I want to print the returned list and everything I try fails. > > I have tried the following: > > printList l = > if length l >= 1 > then do putStrLn (head l) > printList (tail l) > else putStrLn("") > > f = printList askForWords > > and I get > Expression : printList askForWords > *** Term : askForWords > *** Type : IO [[Char]] > *** Does not match : [[Char]] > > I believe one of the following will work for you: > > f = askForWords >>= printList > f = do > words <- askForWords > printList words > > > > > ************************************* > The exercise right below this asks for a very slight modification to read > numbers instead. > > However, I am confused about how to convert strings to numbers. > If I type in the hugs interactive console > read "5" + 3 --> 8 -- ok perfect > > However > read "5" gives > ERROR - Unresolved overloading > *** Type : Read a => a > *** Expression : read "5" > > Yet page 33 of the tutorial has the following code: > doGuessing num = do > putStrLn "Enter your guess:" > guess <- getLine > let guessNum = read guess -- ok in let stmt, but not at repl prompt? > > The problem here is type inference. The statement read "5" has type "(Read > a) => a", which basically means anything that implements the class "Read." > When you do read "5" + 3, the read "5" gets the type of the 3. I assume > that in the latter case, you use the expression guessNum in a way later on > that the compiler can infer its type. > > > > Anyway I take the info that has been presented and create this function: > askForNumbers = do > hSetBuffering stdin LineBuffering > putStrLn "Give me a number (or 0 to stop)" > numStr <- getLine > let num = read numStr > if num == 0 > then return [] > else do > rest <- askForNumbers > return (num : rest) > > However, when I try to use it, like say > > map sqrt askForNumbers > > ERROR - Type error in application > *** Expression : map sqrt askForNumbers > *** Term : askForNumbers > *** Type : IO [Integer] > *** Does not match : [a] > > Similar to above, try this: > do nums <- askForNumbers > map sqrt nums > > > > ********************************************************* > > Is there a way to write printList to handle Strings or numbers? > Or should I write > printList (map show askForNumbers) > > Note: you should probably do this using mapM_, but for simplicity, I'll do > it using explicit recursion: > > printList [] = putStrLn "" -- or return () if you don't want the extra > blank line printList (x:xs) = do putStrLn (show x) > printList xs > > If you have any questions about how these worked, let me know! > > Michael > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From rendel at daimi.au.dk Mon Dec 15 17:45:08 2008 From: rendel at daimi.au.dk (Tillmann Rendel) Date: Mon Dec 15 17:38:25 2008 Subject: [Haskell-beginners] Problems with one of my first examples In-Reply-To: <10776152C3DA8244BAA5D5B10853FE99044E7A28@BULLDOG.iteris.com> References: <10776152C3DA8244BAA5D5B10853FE99044E7A27@BULLDOG.iteris.com> <29bf512f0812151248p163b3101pb9fe83c63685f1bd@mail.gmail.com> <10776152C3DA8244BAA5D5B10853FE99044E7A28@BULLDOG.iteris.com> Message-ID: <4946DDF4.2060702@daimi.au.dk> Jeff C. Britton wrote: > do nums <- askForNumbers; map sqrt nums > > ERROR - Type error in final generator > *** Term : map sqrt nums > *** Type : [Integer] > *** Does not match : IO a Here (map sqrt nums) has type [Integer], so you cannot use it in a do expression for IO. Instead, you have to write something which produces an IO action. > do nums <- askForNumbers; printList nums -- works fine Here, (printList nums) has type IO (), so it fits into the do expression and everything is fine. If you want to print the list of square roots, you have to say so: do nums <- askForNumbers; printList (map sqrt nums) Tillmann From renick at gmail.com Tue Dec 16 01:33:18 2008 From: renick at gmail.com (Renick Bell) Date: Tue Dec 16 01:26:00 2008 Subject: [Haskell-beginners] unix-2.3.1.0 failed during the building phase Message-ID: I was trying to install this package and received this error: [a lot of stuff] Preprocessing library unix-2.3.1.0... Building unix-2.3.1.0... [ 1 of 21] Compiling System.Posix.Signals ( System/Posix/Signals.hs, dist/build/System/Posix/Signals.o ) [ 2 of 21] Compiling System.Posix.Signals.Exts ( dist/build/System/Posix/Signals/Exts.hs, dist/build/System/Posix/Signals/Exts.o ) [ 3 of 21] Compiling System.Posix.User ( dist/build/System/Posix/User.hs, dist/build/System/Posix/User.o ) [ 4 of 21] Compiling System.Posix.Unistd ( dist/build/System/Posix/Unistd.hs, dist/build/System/Posix/Unistd.o ) [ 5 of 21] Compiling System.Posix.Time ( dist/build/System/Posix/Time.hs, dist/build/System/Posix/Time.o ) [ 6 of 21] Compiling System.Posix.Resource ( dist/build/System/Posix/Resource.hs, dist/build/System/Posix/Resource.o ) [ 7 of 21] Compiling System.Posix.Process.Internals ( System/Posix/Process/Internals.hs, dist/build/System/Posix/Process/Internals.o ) [ 8 of 21] Compiling System.Posix.Error ( System/Posix/Error.hs, dist/build/System/Posix/Error.o ) [ 9 of 21] Compiling System.Posix.Files ( dist/build/System/Posix/Files.hs, dist/build/System/Posix/Files.o ) System/Posix/Files.hsc:504:42: Ambiguous occurrence `c_rename' It could refer to either `System.Posix.Files.c_rename', defined at System/Posix/Files.hsc:507:3 or `System.Posix.Internals.c_rename', imported from System.Posix.Internals at System/Posix/Files.hsc:93:0-28 cabal: Error: some packages failed to install: unix-2.3.1.0 failed during the building phase. The exception was: exit: ExitFailure 1 Being a beginner, I'm not sure what to do here... -- Renick Bell http://the3rd2nd.com From mozhgan_kch at yahoo.com Tue Dec 16 05:45:23 2008 From: mozhgan_kch at yahoo.com (Mozhgan) Date: Tue Dec 16 05:38:04 2008 Subject: [Haskell-beginners] MVar and Par .. Message-ID: <48504.12378.qm@web90406.mail.mud.yahoo.com> Hi .. Hope you are doing well . I've just joined this group coz I am really a beginner and have no idea that what I have to do ! Recently, I am struggling to do some simple experiment with haskell language about parallelism and wrong answers that we can get while using a shared variable . I tried to write a simple program, for example calculationg 'n=n+1' few times.And then I tried to do it in parallel by using 'par' and 'pseq' . The aim was to get the wrong answer because we have to share a variable here,and without using 'MVar' function we will get the wrong answer for the calculation . I don't know how to write it in parallel in order to get a wrong answer when we don't use MVar,because we have a shared variable here. I read about MVars as well,but also I don't know how to combine MVar and Par together to get the program to work. I wrote this : module Main where f :: Int -> Int -> Int f i n = g 1 i n where g x i n | x <= i = g (x+1) i (n+1) | otherwise = n main :: IO () main = do putStrLn "starting..." let r = f 10 5 putStrLn (show r) putStrLn "finished" I want to make to work in parallel by using 'Par'.And also use MVar for this simple example to work. All of the example about MVar are a little bit complicated and I couldn't figure it that how can I write one,the same ! Can any one help me with this ? I want a simple example that I can feel the need of MVar when I run my program in parallel and while I am using a shared variable. Regards; Mozhgan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081216/d77e37b6/attachment.htm From apfelmus at quantentunnel.de Tue Dec 16 08:20:54 2008 From: apfelmus at quantentunnel.de (Apfelmus, Heinrich) Date: Tue Dec 16 08:13:39 2008 Subject: [Haskell-beginners] Re: A type level programming question In-Reply-To: <8341e4f40812151406p101192aal97c6a9becf4f3bb9@mail.gmail.com> References: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> <8341e4f40812151406p101192aal97c6a9becf4f3bb9@mail.gmail.com> Message-ID: Levi Stephen wrote: > Justin Bailey wrote: >> Levi Stephen wrote: >>> >>> (!) :: (Pos s, Nat i, i :<: s) => FSVec s a -> i -> a >>> >>> I was wondering if it was possible to write a function of type: >>> >>> elementAt :: FSVec s a -> Int -> a >>> > > I may not have to write this function, but I'm guessing at some stage > it's going to be necessary to convert from value level integers to > type level. Is this a bad guess? Yes and no. Actually, the type for elementAt should be elementAT :: FSVec s a -> Int -> Maybe a So, you can try to fetch an element at a particular index, but it's not guaranteed to work. In contrast, (!) :: (Pos s, Nat i, i :<: s) => FSVec s a -> i -> a is guaranteed to return an element because the index is guaranteed to be in range. The point is that i is usually not obtained from a value level integer, but instead constructed from other type level integers such that the construction vouches that it's in range. Put differently, always using elementAt would be pointless, i.e. you could dispense with type level integers entirely and use a normal list instead. > The type-level library provides the function reifyIntegral for this > purpose, but the continuation is only allowed to rely on the Nat class > constraint. > > I don't know how to implement elementAt yet. FSVec provides the (!) > function for accessing elements, but I need to satisfy the i :<: s > class constraint before calling it. Satisfying the i :<: s constraint means supplying a proof that the integer i is indeed smaller than s . Of course, if the index i is not known statically, you don't have such a proof and you won't be able to obtain one. But what you can do is to construct a different index j that is guaranteed to be smaller than s : j = i `max` pred s No matter what i is, j is always going to fulfill j :<: s. Hence, your function can be written as elementAt :: FSVec s a -> Int -> Maybe a elementAt v i | 0 <= i && i < length v = reifyIntegral i at | otherwise = Nothing where at i = Just $ v ! max i (pred $ lengthT v) (Note that it may be that this code still doesn't compile, for example because the type-level library maybe doesn't automatically deduce j :<: s or because the type checker doesn't accept our proof for some other reason.) Regards, H. Apfelmus From levi.stephen at gmail.com Sun Dec 21 17:17:29 2008 From: levi.stephen at gmail.com (Levi Stephen) Date: Sun Dec 21 17:09:54 2008 Subject: [Haskell-beginners] Re: A type level programming question In-Reply-To: References: <8341e4f40812141511u279cdcbeodbe5f6c6ff6399b0@mail.gmail.com> <8341e4f40812151406p101192aal97c6a9becf4f3bb9@mail.gmail.com> Message-ID: <8341e4f40812211417q65165717i1fce4471e465458c@mail.gmail.com> On Tue, Dec 16, 2008 at 11:50 PM, Apfelmus, Heinrich wrote: > Put differently, always using elementAt would be pointless, i.e. you > could dispense with type level integers entirely and use a normal list > instead. I am finding I need this less than I thought I would. I have been continuing on looking for alternatives and been fine so far. > > Satisfying the i :<: s constraint means supplying a proof that the > integer i is indeed smaller than s . Of course, if the index i is > not known statically, you don't have such a proof and you won't be able > to obtain one. But what you can do is to construct a different index j > that is guaranteed to be smaller than s : > > j = i `max` pred s > > No matter what i is, j is always going to fulfill j :<: s. Hence, > your function can be written as > > elementAt :: FSVec s a -> Int -> Maybe a > elementAt v i > | 0 <= i && i < length v = reifyIntegral i at > | otherwise = Nothing > where > at i = Just $ v ! max i (pred $ lengthT v) > > (Note that it may be that this code still doesn't compile, for example > because the type-level library maybe doesn't automatically deduce j > :<: s or because the type checker doesn't accept our proof for some > other reason.) > I couldn't get something along these lines to type check, but as mentioned above I'm doing ok without it so far. Thanks, Levi From raeck at msn.com Mon Dec 22 08:51:15 2008 From: raeck at msn.com (Raeck Zhao) Date: Mon Dec 22 08:43:52 2008 Subject: [Haskell-beginners] Defining a containing function on polymorphic list Message-ID: I am trying to define a containing function to see if a value is one of the elements within a list which is polymorphic, but failed with the following codes: > contain :: a -> [a] -> Bool > contain x [] = False > contain x (y:ys) = if x == y then True else contain x ys it seems that the problem is the 'operator' == does not support a polymorphic check? Any way can solve the problem? or any alternative solution to achieve the purpose? Thanks! Raeck _________________________________________________________________ It?s the same Hotmail?. If by ?same? you mean up to 70% faster. http://windowslive.com/online/hotmail?ocid=TXT_TAGLM_WL_hotmail_acq_broad1_122008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/b366e3c3/attachment.htm From wagner.andrew at gmail.com Mon Dec 22 09:02:53 2008 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Dec 22 08:55:16 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: The problem here is even slightly deeper than you might realize. For example, what if you have a list of functions. How do you compare two functions to each other to see if they're equal? There is no good way really to do it! So, not only is == not completely polymorphic, but it CAN'T be. There is a nice solution for this, however, and it's very simple: contain :: Eq a -> [a] -> Bool contain x [] = False contain x (y:ys) = if x == y then True else contain x ys The "Eq a" in the type signature says that 'a' must be a member of the 'Eq' typeclass. That says, in turn, that 'a' must have == defined for it. Fortunately, most types have, or can easily derive that definition. Here is the definition of the typeclass: class Eqa where(==):: a -> a -> Bool (/=):: a -> a -> Bool That is, for 'a' to be a member of 'Eq', it must have a == operator which can take 2 values of that type and return a Boolean, saying whether or not they're equal, and it must also have a definition for the /= operator, which is "not equal". These two are also defined in terms of each other, so if you define ==, you get /= for free, and vice versa. That's probably more information than you needed to know, but I hope it helps. 2008/12/22 Raeck Zhao > I am trying to define a containing function to see if a value is one of > the elements within a list which is polymorphic, but failed with the > following codes: > > contain :: a -> [a] -> Bool > > contain x [] = False > > contain x (y:ys) = if x == y then True else contain x ys it seems that > the problem is the 'operator' == does not support a polymorphic check? > Any way can solve the problem? or any alternative solution to achieve the > purpose? > Thanks! > Raeck > > ------------------------------ > It's the same Hotmail(R). If by "same" you mean up to 70% faster. Get your > account now. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/58d29b34/attachment-0001.htm From wagner.andrew at gmail.com Mon Dec 22 09:18:37 2008 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Dec 22 09:11:11 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: <6dbd4d000812220617s4f79aee6v31e92585d9fad9c1@mail.gmail.com> References: <6dbd4d000812220617s4f79aee6v31e92585d9fad9c1@mail.gmail.com> Message-ID: Yes, of course, sorry for the typo. On Mon, Dec 22, 2008 at 9:17 AM, Denis Bueno wrote: > 2008/12/22 Andrew Wagner : > > The problem here is even slightly deeper than you might realize. For > > example, what if you have a list of functions. How do you compare two > > functions to each other to see if they're equal? There is no good way > really > > to do it! So, not only is == not completely polymorphic, but it CAN'T be. > > > > There is a nice solution for this, however, and it's very simple: > > > > contain :: Eq a -> [a] -> Bool > > Please note that the syntax here should be: > > contain :: Eq a => a -> [a] -> Bool > > Denis > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/bf05cd3c/attachment.htm From raeck at msn.com Mon Dec 22 09:35:01 2008 From: raeck at msn.com (Raeck Zhao) Date: Mon Dec 22 09:27:23 2008 Subject: [Haskell-beginners] RE: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: Thank you very much for your reply! It is really helpful! But I just found another 'problem', I just realize that the list does not support the user-defined data type? the list is also depending on the Eq function? For example, data Shape = Square | Triangle | Circle when I type either [Square, Triangle, Circle] or Square == Square there are errors! So there is no way to construct a truly polymorphic List? any way to extend the list to support some user-defined data type? Or... I define the Shape in a wrong way actually? Thanks Raeck Date: Mon, 22 Dec 2008 09:02:53 -0500 From: wagner.andrew@gmail.com To: raeck@msn.com Subject: Re: [Haskell-cafe] Defining a containing function on polymorphic list CC: haskell-cafe@haskell.org; beginners@haskell.org The problem here is even slightly deeper than you might realize. For example, what if you have a list of functions. How do you compare two functions to each other to see if they're equal? There is no good way really to do it! So, not only is == not completely polymorphic, but it CAN'T be. There is a nice solution for this, however, and it's very simple: contain :: Eq a -> [a] -> Bool contain x [] = False contain x (y:ys) = if x == y then True else contain x ys The "Eq a" in the type signature says that 'a' must be a member of the 'Eq' typeclass. That says, in turn, that 'a' must have == defined for it. Fortunately, most types have, or can easily derive that definition. Here is the definition of the typeclass: class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool That is, for 'a' to be a member of 'Eq', it must have a == operator which can take 2 values of that type and return a Boolean, saying whether or not they're equal, and it must also have a definition for the /= operator, which is "not equal". These two are also defined in terms of each other, so if you define ==, you get /= for free, and vice versa. That's probably more information than you needed to know, but I hope it helps. 2008/12/22 Raeck Zhao I am trying to define a containing function to see if a value is one of the elements within a list which is polymorphic, but failed with the following codes: > contain :: a -> [a] -> Bool > contain x [] = False > contain x (y:ys) = if x == y then True else contain x ys it seems that the problem is the 'operator' == does not support a polymorphic check? Any way can solve the problem? or any alternative solution to achieve the purpose? Thanks! Raeck It's the same Hotmail?. If by "same" you mean up to 70% faster. Get your account now. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe _________________________________________________________________ Life on your PC is safer, easier, and more enjoyable with Windows Vista?. http://clk.atdmt.com/MRT/go/127032870/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/4762dfff/attachment.htm From wagner.andrew at gmail.com Mon Dec 22 09:44:41 2008 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Mon Dec 22 09:37:15 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: There are two ways to fix this. Let me see if I can get my syntax right this time :) 1.) Let GHC work out the Eq instance: data Shape = Square | Triangle | Circle deriving Eq 2.) Tell GHC how to do it explicitly: data Shape = Square | Triangle | Circle instance Eq Shape where Square == Square = True Triangle == Triangle = True Circle == Circle = True _ == _ = False Note that the last line here means that any other comparisons are false. On Mon, Dec 22, 2008 at 9:35 AM, Raeck Zhao wrote: > Thank you very much for your reply! It is really helpful! > > But I just found another 'problem', I just realize that the list does not > support the user-defined data type? > the list is also depending on the Eq function? > > For example, > > data Shape = Square | Triangle | Circle > > when I type either > > [Square, Triangle, Circle] > > or > > Square == Square > > there are errors! > > So there is no way to construct a truly polymorphic List? any way to extend > the list to support some user-defined data type? > > Or... I define the Shape in a wrong way actually? > > Thanks > > Raeck > > > ------------------------------ > Date: Mon, 22 Dec 2008 09:02:53 -0500 > From: wagner.andrew@gmail.com > To: raeck@msn.com > Subject: Re: [Haskell-cafe] Defining a containing function on polymorphic > list > CC: haskell-cafe@haskell.org; beginners@haskell.org > > The problem here is even slightly deeper than you might realize. For > example, what if you have a list of functions. How do you compare two > functions to each other to see if they're equal? There is no good way really > to do it! So, not only is == not completely polymorphic, but it CAN'T be. > > There is a nice solution for this, however, and it's very simple: > > contain :: Eq a -> [a] -> Bool > contain x [] = False > contain x (y:ys) = if x == y then True else contain x ys > > The "Eq a" in the type signature says that 'a' must be a member of the 'Eq' > typeclass. That says, in turn, that 'a' must have == defined for it. > Fortunately, most types have, or can easily derive that definition. Here is > the definition of the typeclass: > > class Eqa > where (==):: a -> a -> > Bool > (/=):: a -> a -> > Bool > That is, for 'a' to be a member of 'Eq', it must have a == operator which > can take 2 values of that type and return a Boolean, saying whether or not > they're equal, and it must also have a definition for the /= operator, which > is "not equal". These two are also defined in terms of each other, so if you > define ==, you get /= for free, and vice versa. > > That's probably more information than you needed to know, but I hope it > helps. > > 2008/12/22 Raeck Zhao > > I am trying to define a containing function to see if a value is one of > the elements within a list which is polymorphic, but failed with the > following codes: > > contain :: a -> [a] -> Bool > > contain x [] = False > > contain x (y:ys) = if x == y then True else contain x ys it seems that > the problem is the 'operator' == does not support a polymorphic check? > Any way can solve the problem? or any alternative solution to achieve the > purpose? > Thanks! > Raeck > > ------------------------------ > It's the same Hotmail(R). If by "same" you mean up to 70% faster. Get your > account now. > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > > > ------------------------------ > Life on your PC is safer, easier, and more enjoyable with Windows Vista(R). See > how > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/9c4469da/attachment.htm From raeck at msn.com Tue Dec 23 20:45:05 2008 From: raeck at msn.com (Raeck Zhao) Date: Tue Dec 23 20:37:23 2008 Subject: [Haskell-beginners] about the pattern matching In-Reply-To: <7ca3f0160812221101yaa51da9s9d158f08cbb2150a@mail.gmail.com> References: <7ca3f0160812221101yaa51da9s9d158f08cbb2150a@mail.gmail.com> Message-ID: hi, good ... morning : ) I am just confused by the following code > oneOnly :: [Int] > oneOnly = [1] > isOneOnly :: [Int] -> Bool > isOneOnly oneOnly = True > isOneOnly tester = False what I want to do is to define a 'type' oneOnly as [1] and use it on the pattern matching in function isOneOnly. But it does not work as I expect: When I type isOneOnly [1] it will be True which is the result I expect but for is OneOnly [1,2] the result keeps True, it seems the second pattern has been ignored, I think I try to achieve the purpose in a wrong way, any suggestion? Thanks and Merry Christmas Best wishes, Raeck _________________________________________________________________ Send e-mail anywhere. No map, no compass. http://windowslive.com/oneline/hotmail?ocid=TXT_TAGLM_WL_hotmail_acq_anywhere_122008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081224/c0486455/attachment-0001.htm From wagner.andrew at gmail.com Tue Dec 23 21:30:45 2008 From: wagner.andrew at gmail.com (Andrew Wagner) Date: Tue Dec 23 21:23:00 2008 Subject: [Haskell-beginners] about the pattern matching In-Reply-To: References: <7ca3f0160812221101yaa51da9s9d158f08cbb2150a@mail.gmail.com> Message-ID: The line "isOneOnly oneOnly = True" doesn't do what you expect here. Basically, it says there are no constraints on the input, and it binds whatever input it gets to a new *local* variable named oneOnly. Thus, it always matches that line of the function, and always returns true. The problem here is that [1] is a value, not a type that you can match on. If you want to make sure the value is [1], you can do it one of these two ways: isOneOnly x = x == [1] or isOneOnly x | x == [1] = True isOneOnly x | otherwise = False Now at this point you may be wondering how functions like this work: factorial 1 = 1 factorial n = n * factorial (n-1) I just said that you can't match against values, but against types. What gives? Well, in fact, haskell matches against integers as types of sort, of the structure Succ Int. That is, it treats integers like they were encoded with the following type: data Nat = Zero | Succ Nat Now you can see how it could pattern match against integers, just like it would against other types with data constructors. Anyway, I"m sure this is far more information than you wanted to know. On Tue, Dec 23, 2008 at 7:45 PM, Raeck Zhao wrote: > hi, good ... morning : ) > I am just confused by the following code > > > oneOnly :: [Int] > > oneOnly = [1] > > isOneOnly :: [Int] -> Bool > > isOneOnly oneOnly = True > > isOneOnly tester = False > > what I want to do is to define a 'type' oneOnly as [1] and use it on > the pattern matching in function isOneOnly. But it does not work as > I expect: > > When I type > > isOneOnly [1] > > it will be True which is the result I expect but for > > is OneOnly [1,2] > > the result keeps True, it seems the second pattern has been ignored, > I think I try to achieve the purpose in a wrong way, any suggestion? > > Thanks and Merry Christmas > > Best wishes, > Raeck > > ------------------------------ > Send e-mail anywhere. No map, no compass. Get your Hotmail(R) account now. > > _______________________________________________ > 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/20081223/7c7ff8f0/attachment.htm From daniel.is.fischer at web.de Tue Dec 23 21:39:52 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Tue Dec 23 21:29:39 2008 Subject: [Haskell-beginners] about the pattern matching In-Reply-To: References: <7ca3f0160812221101yaa51da9s9d158f08cbb2150a@mail.gmail.com> Message-ID: <200812240339.52803.daniel.is.fischer@web.de> Am Mittwoch, 24. Dezember 2008 02:45 schrieb Raeck Zhao: > hi, good ... morning : ) > I am just confused by the following code > > > oneOnly :: [Int] > > oneOnly = [1] > > isOneOnly :: [Int] -> Bool > > isOneOnly oneOnly = True > > isOneOnly tester = False > > what I want to do is to define a 'type' oneOnly as [1] and use it on > the pattern matching in function isOneOnly. But it does not work as > I expect: > > When I type > > isOneOnly [1] > > it will be True which is the result I expect but for > > is OneOnly [1,2] > > the result keeps True, it seems the second pattern has been ignored, > I think I try to achieve the purpose in a wrong way, any suggestion? In "isOneOnly oneOnly ", the pattern oneOnly is a variable pattern, it matches everything, it also matches [] and _|_. the fact that it is also the name of an entity defined elsewhere doesn't matter. You can find more about pattern matching (basically, a pattern is a wildcard, a variable or a constructor applied to patterns) in the report. If you turn on warnings for overlapping patterns, GHC will warn you: $ ghci -fwarn-overlapping-patterns OneOnly GHCi, version 6.8.3: http://www.haskell.org/ghc/ :? for help Loading package base ... linking ... done. [1 of 1] Compiling Main ( OneOnly.hs, interpreted ) OneOnly.hs:4:0: Warning: Pattern match(es) are overlapped In the definition of `isOneOnly': isOneOnly tester = ... Ok, modules loaded: Main. *Main> isOneOnly undefined True Depending on what you want to achieve, maybe isOneOnly [1] = True isOneOnly _ = False or isOneOnly [_] = True isOneOnly _ = False is the solution. > > Thanks and Merry Christmas > > Best wishes, > Raeck > From dbueno at gmail.com Mon Dec 22 09:17:25 2008 From: dbueno at gmail.com (Denis Bueno) Date: Tue Dec 23 21:38:05 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: <6dbd4d000812220617s4f79aee6v31e92585d9fad9c1@mail.gmail.com> 2008/12/22 Andrew Wagner : > The problem here is even slightly deeper than you might realize. For > example, what if you have a list of functions. How do you compare two > functions to each other to see if they're equal? There is no good way really > to do it! So, not only is == not completely polymorphic, but it CAN'T be. > > There is a nice solution for this, however, and it's very simple: > > contain :: Eq a -> [a] -> Bool Please note that the syntax here should be: contain :: Eq a => a -> [a] -> Bool Denis From lrpalmer at gmail.com Mon Dec 22 14:01:09 2008 From: lrpalmer at gmail.com (Luke Palmer) Date: Tue Dec 23 21:38:19 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: <7ca3f0160812221101yaa51da9s9d158f08cbb2150a@mail.gmail.com> 2008/12/22 Raeck Zhao > Thank you very much for your reply! It is really helpful! > > But I just found another 'problem', I just realize that the list does not > support the user-defined data type? > the list is also depending on the Eq function? > > For example, > > data Shape = Square | Triangle | Circle > > when I type either > > [Square, Triangle, Circle] > This is perfectly legal, but GHCi won't be able to print it, because there is no Show instance for Shape. You can declare one: instance Show Shape where show Square = "Square" show Triagle = "Triangle" show Circle = "Circle" This can be generated automatically when you declare the type, by using: data Shape = Square | Triangle | Circle deriving (Show) > > > or > > Square == Square > Similarly, to use (==), you need an Eq instance, which can be defined much in the same way as the Show instance above (deriving also works on Eq -- don't generalize too hastily; not all classes work with deriving). Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/d91c3e78/attachment.htm From tom.davie at gmail.com Mon Dec 22 09:31:35 2008 From: tom.davie at gmail.com (Thomas Davie) Date: Tue Dec 23 21:38:31 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: <6dbd4d000812220617s4f79aee6v31e92585d9fad9c1@mail.gmail.com> Message-ID: On 22 Dec 2008, at 15:18, Andrew Wagner wrote: > Yes, of course, sorry for the typo. > > On Mon, Dec 22, 2008 at 9:17 AM, Denis Bueno wrote: > 2008/12/22 Andrew Wagner : > > The problem here is even slightly deeper than you might realize. For > > example, what if you have a list of functions. How do you compare > two > > functions to each other to see if they're equal? There is no good > way really > > to do it! So, not only is == not completely polymorphic, but it > CAN'T be. > > > > There is a nice solution for this, however, and it's very simple: > > > > contain :: Eq a -> [a] -> Bool > > Please note that the syntax here should be: > > contain :: Eq a => a -> [a] -> Bool > > Denis Of note, unless this is an exercise, such a function already exists -- it's called elem. How do you find such a function? You search on haskell.org/hoogle. http://haskell.org/hoogle/?hoogle=Eq+a+%3D%3E+a+-%3E+%5Ba%5D+-%3E+Bool Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081222/ad44253f/attachment.htm From ryani.spam at gmail.com Wed Dec 24 10:07:14 2008 From: ryani.spam at gmail.com (Ryan Ingram) Date: Wed Dec 24 23:21:26 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: References: Message-ID: <2f9b2d30812240707u5af8c546t5b7c25846a4fcc04@mail.gmail.com> Here's a tip: leave off the type signature, and ask ghci what it is. $ ghci Prelude> let contain x [] = False ; contain x (y:ys) = if x == y then True else contain x ys Prelude> :t contain contain :: (Eq a) => a -> [a] -> Bool -- ryan 2008/12/22 Raeck Zhao : > I am trying to define a containing function to see if a value is one of the > elements within a list which is polymorphic, but failed with the following > codes: >> contain :: a -> [a] -> Bool >> contain x [] = False >> contain x (y:ys) = if x == y then True else contain x ys it seems that the >> problem is the 'operator' == does not support a polymorphic check? > Any way can solve the problem? or any alternative solution to achieve the > purpose? > Thanks! > Raeck > > ________________________________ > It's the same Hotmail(R). If by "same" you mean up to 70% faster. Get your > account now. > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe@haskell.org > http://www.haskell.org/mailman/listinfo/haskell-cafe > > From frantisek.kocun at gmail.com Wed Dec 24 10:36:20 2008 From: frantisek.kocun at gmail.com (frantisek kocun) Date: Wed Dec 24 23:21:37 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] Defining a containing function on polymorphic list In-Reply-To: <2f9b2d30812240707u5af8c546t5b7c25846a4fcc04@mail.gmail.com> References: <2f9b2d30812240707u5af8c546t5b7c25846a4fcc04@mail.gmail.com> Message-ID: Hi Raeck, as I see what types you defined, don't you doing School of Expression? (In summer I made my way to FAL chapter, but I had no time more (school), but I will definitely finish that book:) Fero -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081224/5f271f7b/attachment.htm From jeedward at yahoo.com Sat Dec 27 15:59:23 2008 From: jeedward at yahoo.com (Ed) Date: Sat Dec 27 15:51:33 2008 Subject: [Haskell-beginners] MULTICONF-09 call for papers Message-ID: <671277.77901.qm@web45906.mail.sp1.yahoo.com> MULTICONF-09 call for papers ? The 2009 Multi Conference in Computer Science, Information Technology and Control systems and Computational Science and Computer Engineering (MULTICONF-09) (website: http://www.PromoteResearch.org) will be held during July 13-16 2009 in Orlando, FL, USA. We invite draft paper submissions. The event consists of the following conferences: ????????? International Conference on Artificial Intelligence and Pattern Recognition (AIPR-09) ????????? International Conference on Automation, Robotics and Control Systems (ARCS-09) ????????? International Conference on Bioinformatics, Computational Biology, Genomics and Chemoinformatics (BCBGC-09) ????????? International Conference on Enterprise Information Systems and Web Technologies (EISWT-09) ????????? International Conference on High Performance Computing, Networking and Communication Systems (HPCNCS-09) ????????? International Conference on Information Security and Privacy (ISP-09) ????????? International Conference on Recent Advances in Information Technology and Applications (RAITA-09) ????????? International Conference on Software Engineering Theory and Practice (SETP-09) ????????? International Conference on Theory and Applications of Computational Science (TACS-09) ????????? International Conference on Theoretical and Mathematical Foundations of Computer Science (TMFCS-09) ? The website http://www.PromoteResearch.org? contains more details. ? Sincerely John Edward Publicity committee ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081227/43bde7f6/attachment.htm From colin at colina.demon.co.uk Sun Dec 28 04:07:08 2008 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Sun Dec 28 03:59:12 2008 Subject: [Haskell-beginners] Restricting integers in a type? Message-ID: Hello, I want to declare a type thus: type Coordinate = (Int, Int) But the two integers must be confined to the inclusive range 0-11. Can i express that in the type system? -- Colin Adams Preston Lancashire From es at ertes.de Sun Dec 28 10:26:10 2008 From: es at ertes.de (Ertugrul Soeylemez) Date: Sun Dec 28 10:22:07 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? References: Message-ID: <20081228162610.5994152e@tritium.xx> Colin Paul Adams wrote: > I want to declare a type thus: > > type Coordinate = (Int, Int) > > But the two integers must be confined to the inclusive range 0-11. Can > i express that in the type system? Well, the type system allows you to create your own ranged integer type. Here is a rather inflexible, but working method to do it: newtype Int12 = Int12 Int deriving (Eq, Read, Show) instance Num Int12 where Int12 x + Int12 y | x+y <= 11 = Int12 (x+y) | otherwise = error "Int12 addition out of range" ... Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From colin at colina.demon.co.uk Sun Dec 28 10:56:14 2008 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Sun Dec 28 10:48:31 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? In-Reply-To: <20081228162610.5994152e@tritium.xx> (Ertugrul Soeylemez's message of "Sun\, 28 Dec 2008 16\:26\:10 +0100") References: <20081228162610.5994152e@tritium.xx> Message-ID: >>>>> "Ertugrul" == Ertugrul Soeylemez writes: Ertugrul> Colin Paul Adams wrote: >> I want to declare a type thus: >> >> type Coordinate = (Int, Int) >> >> But the two integers must be confined to the inclusive range >> 0-11. Can i express that in the type system? Ertugrul> Well, the type system allows you to create your own Ertugrul> ranged integer type. Here is a rather inflexible, but Ertugrul> working method to do it: Ertugrul> newtype Int12 = Int12 Int deriving (Eq, Read, Show) Ertugrul> instance Num Int12 where Int12 x + Int12 y | x+y <= 11 Ertugrul> = Int12 (x+y) | otherwise = error "Int12 addition out of Ertugrul> range" ... That would seem to allow x = -3 and y = 13, for instance. -- Colin Adams Preston Lancashire From tom.davie at gmail.com Sun Dec 28 11:08:21 2008 From: tom.davie at gmail.com (Thomas Davie) Date: Sun Dec 28 11:00:28 2008 Subject: [Haskell-beginners] Restricting integers in a type? In-Reply-To: References: Message-ID: type Coordinate = (RInt,RInt) data RInt = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Eleven You might also want to add an instance of Num so that you can define them simply by typing the relevant number, but then you'll lose the type system checking the bounds. Bob On 28 Dec 2008, at 10:07, Colin Paul Adams wrote: > Hello, > > I want to declare a type thus: > > type Coordinate = (Int, Int) > > But the two integers must be confined to the inclusive range 0-11. Can > i express that in the type system? > -- > Colin Adams > Preston Lancashire > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From es at ertes.de Sun Dec 28 17:47:16 2008 From: es at ertes.de (Ertugrul Soeylemez) Date: Sun Dec 28 17:39:29 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? References: <20081228162610.5994152e@tritium.xx> Message-ID: <20081228234716.4b734289@tritium.xx> Colin Paul Adams wrote: > Ertugrul> Well, the type system allows you to create your own > Ertugrul> ranged integer type. Here is a rather inflexible, but > Ertugrul> working method to do it: > > Ertugrul> newtype Int12 = Int12 Int deriving (Eq, Read, Show) > > Ertugrul> instance Num Int12 where Int12 x + Int12 y | x+y <= 11 > Ertugrul> = Int12 (x+y) | otherwise = error "Int12 addition out of > Ertugrul> range" ... > > That would seem to allow x = -3 and y = 13, for instance. Not if you disallow an x = -3 and y = 13 to happen in the first place. Haskell's module and type system allows you to do that. Greets, Ertugrul. -- Key-ID: E5DD8D11 "Ertugrul Soeylemez " FPrint: 0F12 0912 DFC8 2FC5 E2B8 A23E 6BAC 998E CE40 2012 Keysrv: hkp://subkeys.pgp.net/ -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From gjk.liu at gmail.com Sun Dec 28 22:22:04 2008 From: gjk.liu at gmail.com (Liu Jian) Date: Sun Dec 28 22:14:05 2008 Subject: [Haskell-beginners] about Data.BinaryTree Message-ID: <8c2dc7030812281922q60c61ce7n87a655a5f4cd32@mail.gmail.com> Hi All, Is there any implementation of binary tree in haskell library? for example, "insert lookup empty adjust isEmpty delete" including in it. cheers, --- email to: gjk.liu@gmail.com From raeck at msn.com Mon Dec 29 00:04:28 2008 From: raeck at msn.com (Raeck chiu) Date: Sun Dec 28 23:56:30 2008 Subject: [Haskell-beginners] represent data sturcture using function Message-ID: Merry Christmas! Hope everybody is enjoying the Christmas! I am doing some readings and I found something seems to be interesting. People sometime will try to represent a quantity-regard-only data structure (such a order-regadless List) using functions instead of ta concrete data structure (like the haskell build-in []), any particular reason for this? For example, > data Sex = Male | Female > classA :: Sex -> Int > classA Male = 100 > classA Female = 200 when I should prefer the above solution instead of using a concrete data structure such as [] to represent the classA members? It seems to be very difficult to change the number of Male or Female if a concrete data structure is not used. Is it possible change the number of Male in classA when represent classA using function? Thank you very much! Best wishes, Raeck _________________________________________________________________ It?s the same Hotmail?. If by ?same? you mean up to 70% faster. http://windowslive.com/online/hotmail?ocid=TXT_TAGLM_WL_hotmail_acq_broad1_122008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081229/78f7e2f7/attachment.htm From daniel.is.fischer at web.de Mon Dec 29 01:06:26 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Mon Dec 29 00:55:57 2008 Subject: [Haskell-beginners] about Data.BinaryTree In-Reply-To: <8c2dc7030812281922q60c61ce7n87a655a5f4cd32@mail.gmail.com> References: <8c2dc7030812281922q60c61ce7n87a655a5f4cd32@mail.gmail.com> Message-ID: <200812290706.26856.daniel.is.fischer@web.de> Am Montag, 29. Dezember 2008 04:22 schrieb Liu Jian: > Hi All, > > Is there any implementation of binary tree in haskell library? for > example, "insert lookup empty adjust isEmpty delete" including in > it. > > cheers, Well, depending on your use-case, it might be worth looking at Data.Set and Data.Map, they're implemented via binary trees. There's an AVL-tree imlementation in http://hackage.haskell.org/cgi-bin/hackage-scripts/package/collections And generally a lot of data structures on Hackage, suffix-trees, finger-trees... There should be something that suits your needs. Cheers, Daniel From colin at colina.demon.co.uk Mon Dec 29 01:37:12 2008 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Mon Dec 29 01:29:13 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? In-Reply-To: <20081228234716.4b734289@tritium.xx> (Ertugrul Soeylemez's message of "Sun\, 28 Dec 2008 23\:47\:16 +0100") References: <20081228162610.5994152e@tritium.xx> <20081228234716.4b734289@tritium.xx> Message-ID: >>>>> "Ertugrul" == Ertugrul Soeylemez writes: >> That would seem to allow x = -3 and y = 13, for instance. Ertugrul> Not if you disallow an x = -3 and y = 13 to happen in Ertugrul> the first place. Haskell's module and type system Ertugrul> allows you to do that. Can you explain how to do that please? -- Colin Adams Preston Lancashire From raeck at msn.com Mon Dec 29 20:24:00 2008 From: raeck at msn.com (raeck@msn.com) Date: Mon Dec 29 20:16:22 2008 Subject: [Haskell-beginners] 'Iterating a data type' In-Reply-To: <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> Message-ID: Are there anyway to express the "iterating" of a user-defined data type in Haskell? For example, in > data Shape = Square | Circle | Triangle how can I 'iterate' them and apply them all to the same function without indicating them explicitly? such as [func Square, func Circle, func Triangle]. Can I use a form similar to the following case in a list instead: > Numbers = [1,2,3,4,5] > [func x | x <- Numbers ] Actually what I want is to obtain all the possible values of a data type (Shape). Thank you very much! Best wishes, Raeck From es at ertes.de Tue Dec 30 04:13:15 2008 From: es at ertes.de (Ertugrul Soeylemez) Date: Tue Dec 30 04:05:28 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? References: <20081228162610.5994152e@tritium.xx> <20081228234716.4b734289@tritium.xx> Message-ID: <20081230101315.4692acba@tritium.xx> Colin Paul Adams wrote: > >>>>> "Ertugrul" == Ertugrul Soeylemez writes: > > >> That would seem to allow x = -3 and y = 13, for instance. > > Ertugrul> Not if you disallow an x = -3 and y = 13 to happen in > Ertugrul> the first place. Haskell's module and type system > Ertugrul> allows you to do that. > > Can you explain how to do that please? Sure: module Even (Even) where newtype Even a = Even a deriving (Eq, Show) instance Integral a => Num (Even a) where Even a + Even b = Even (a+b) -- ... fromInteger x = if even x then Even (fromInteger x) else undefined The only way to introduce incorrect Even values would be to access the constructor directly, but in that example, it's not exported. The interface to constructing Even values is the fromInteger function. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/ From colin at colina.demon.co.uk Tue Dec 30 04:15:42 2008 From: colin at colina.demon.co.uk (Colin Paul Adams) Date: Tue Dec 30 04:07:41 2008 Subject: [Haskell-beginners] Re: Restricting integers in a type? In-Reply-To: <20081230101315.4692acba@tritium.xx> (Ertugrul Soeylemez's message of "Tue\, 30 Dec 2008 10\:13\:15 +0100") References: <20081228162610.5994152e@tritium.xx> <20081228234716.4b734289@tritium.xx> <20081230101315.4692acba@tritium.xx> Message-ID: >>>>> "Ertugrul" == Ertugrul Soeylemez writes: Ertugrul> Colin Paul Adams wrote: >> >>>>> "Ertugrul" == Ertugrul Soeylemez writes: >> >> >> That would seem to allow x = -3 and y = 13, for instance. >> Ertugrul> Not if you disallow an x = -3 and y = 13 to happen in Ertugrul> the first place. Haskell's module and type system Ertugrul> allows you to do that. >> >> Can you explain how to do that please? Ertugrul> Sure: Ertugrul> module Even (Even) where Ertugrul> newtype Even a = Even a deriving (Eq, Show) Ertugrul> instance Integral a => Num (Even a) where Even a + Ertugrul> Even b = Even (a+b) -- ... fromInteger x = if even x Ertugrul> then Even (fromInteger x) else undefined Ertugrul> The only way to introduce incorrect Even values would be Ertugrul> to access the constructor directly, but in that example, Ertugrul> it's not exported. The interface to constructing Even Ertugrul> values is the fromInteger function. Thanks for all your help. -- Colin Adams Preston Lancashire From mail at paulvisschers.net Tue Dec 30 05:30:17 2008 From: mail at paulvisschers.net (Paul Visschers) Date: Tue Dec 30 05:22:05 2008 Subject: [Haskell-beginners] 'Iterating a data type' In-Reply-To: References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> Message-ID: <4959F839.6050908@paulvisschers.net> You actually have two different questions. The first about iteration can be done by the function map in the following way: Instead of [func Square, func Circle, func Triangle] you use: map func [Square, Circle, Triangle]. The list comprehensions should also work: [func x | x <- [Square, Circle, Triangle]] Now as for obtaining/generating all values of Shape, the easiest way is to make Shape an instance of Enum, like this: data Shape = Square | Circle | Triangle deriving Enum You can then generate a list of all the values by: enumFrom Square You use Square here because it is the first constructor of Shape, and you want to enumerate them all. I hope this helps, Paul raeck@msn.com wrote: > Are there anyway to express the "iterating" of a user-defined data type > in Haskell? > > For example, in > >> data Shape = Square | Circle | Triangle > > how can I 'iterate' them and apply them all to the same function without > indicating them explicitly? > such as [func Square, func Circle, func Triangle]. > Can I use a form similar to the following case in a list instead: > >> Numbers = [1,2,3,4,5] > >> [func x | x <- Numbers ] > > Actually what I want is to obtain all the possible values of a data type > (Shape). > > Thank you very much! > > Best wishes, > > Raeck > _______________________________________________ > Beginners mailing list > Beginners@haskell.org > http://www.haskell.org/mailman/listinfo/beginners From raeck at msn.com Tue Dec 30 12:12:29 2008 From: raeck at msn.com (raeck@msn.com) Date: Tue Dec 30 12:04:28 2008 Subject: [Haskell-beginners] Enum and Bounded in generic type In-Reply-To: <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> Message-ID: Hi, how can I make the following code work? (show all the possible values of a type 'a') > showAll :: (Eq a, Bounded a, Enum a) => a -> [a] > showAll a = [minBound..maxBound]::[a] it keeps saying that I could fix the problem by adding (Enum a) and (Bounded a) the the context, but I failed when I try. anything goes wrong? Thanks! Raeck From flippa at flippac.org Tue Dec 30 12:17:37 2008 From: flippa at flippac.org (Philippa Cowderoy) Date: Tue Dec 30 12:09:40 2008 Subject: [Haskell-beginners] Enum and Bounded in generic type In-Reply-To: References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> Message-ID: <1230657457.1125.1048.camel@flippa-eee> [-cafe left out] On Tue, 2008-12-30 at 17:12 +0000, raeck@msn.com wrote: > Hi, how can I make the following code work? (show all the possible values of > a type 'a') > > > showAll :: (Eq a, Bounded a, Enum a) => a -> [a] > > showAll a = [minBound..maxBound]::[a] > > it keeps saying that I could fix the problem by adding (Enum a) and (Bounded > a) the the context, but I failed when I try. > The problem is the inner annotation, ::[a]. It's not the same a as in (Eq a, Bounded a, Enum a) => a -> [a], and in Haskell98 it can't be. I'm not surprised that's confused you! If you remove the inner annotation it should work fine though. You can go a step further and make showAll a value rather than a function: showAll = [minBound..maxBound] (I've left out the type annotations, but you can put ":t [minBound..maxBound]" into ghci or hugs if you want one) -- Philippa Cowderoy I left the snappy .sigs on the other computer From mail at paulvisschers.net Tue Dec 30 12:50:22 2008 From: mail at paulvisschers.net (Paul Visschers) Date: Tue Dec 30 12:42:06 2008 Subject: [Haskell-beginners] Enum and Bounded in generic type In-Reply-To: <1230657457.1125.1048.camel@flippa-eee> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> <1230657457.1125.1048.camel@flippa-eee> Message-ID: <495A5F5E.70602@paulvisschers.net> You seem to be having some trouble with the type system, not just in this instance. I found when I was learning Haskell that when this happens, it is useful to not add type annotations, then load it up in GHCi and see what it comes up with (with the aforementions :t option). Then you can see why that makes sense and possibly change the function. Once you're happy with the function and are confident you understand its type, go ahead and put the type annotation back into your source code. I also found it useful to play around with various expressions and see what their types where. Especially with things like partial application, function composition and monadic functions. Paul Philippa Cowderoy wrote: > [-cafe left out] > > On Tue, 2008-12-30 at 17:12 +0000, raeck@msn.com wrote: >> Hi, how can I make the following code work? (show all the possible values of >> a type 'a') >> >>> showAll :: (Eq a, Bounded a, Enum a) => a -> [a] >>> showAll a = [minBound..maxBound]::[a] >> it keeps saying that I could fix the problem by adding (Enum a) and (Bounded >> a) the the context, but I failed when I try. >> > > The problem is the inner annotation, ::[a]. It's not the same a as in > (Eq a, Bounded a, Enum a) => a -> [a], and in Haskell98 it can't be. I'm > not surprised that's confused you! If you remove the inner annotation it > should work fine though. > > You can go a step further and make showAll a value rather than a > function: > > showAll = [minBound..maxBound] > > (I've left out the type annotations, but you can put ":t > [minBound..maxBound]" into ghci or hugs if you want one) > From nathanmholden at gmail.com Tue Dec 30 22:41:02 2008 From: nathanmholden at gmail.com (Nathan Holden) Date: Tue Dec 30 22:32:58 2008 Subject: [Haskell-beginners] IO Question Message-ID: <305228b20812301941t781efe6ajf51e644de1255d86@mail.gmail.com> I've been playing around with some types, and such, and I can get some basic IO. But the thing that confused me is this: How is it that IO [Char] == [Char] can be True, but IO a == a is a type error? How can you implement eq for a type so that IO (type) == type? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081230/338c9178/attachment.htm From alexander.dunlap at gmail.com Tue Dec 30 23:36:22 2008 From: alexander.dunlap at gmail.com (Alexander Dunlap) Date: Tue Dec 30 23:28:16 2008 Subject: [Haskell-beginners] IO Question In-Reply-To: <305228b20812301941t781efe6ajf51e644de1255d86@mail.gmail.com> References: <305228b20812301941t781efe6ajf51e644de1255d86@mail.gmail.com> Message-ID: <57526e770812302036x573c6ebam11b0c6c1d8aa565c@mail.gmail.com> On Tue, Dec 30, 2008 at 7:41 PM, Nathan Holden wrote: > I've been playing around with some types, and such, and I can get some basic > IO. But the thing that confused me is this: How is it that IO [Char] == > [Char] can be True, but IO a == a is a type error? How can you implement eq > for a type so that IO (type) == type? The Eq type class is essentially defined as such: class Eq a where (==) :: a -> a -> Bool I don't know how you are even calling (==) on objects of type IO [Char] and [Char], since the type signature of (==) says that both of its arguments have to have the same type. Could you give more details of what is going on? Alex From max.cs.2009 at googlemail.com Wed Dec 31 10:02:48 2008 From: max.cs.2009 at googlemail.com (Max cs) Date: Wed Dec 31 09:54:42 2008 Subject: [Haskell-beginners] about the concatenation on a tree In-Reply-To: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> References: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> Message-ID: <902ff3e80812310702y7b2e4c28g356baffbb8df678@mail.gmail.com> hi all, not sure if there is someone still working during holiday like me : ) I got a little problem in implementing some operations on tree. suppose we have a tree date type defined: data Tree a = Leaf a | Branch (Tree a) (Tree a) I want to do a concatenation on these tree just like the concat on list. Anyone has idea on it? or there are some existing implementation? Thank you and Happy New Year! regards, Max -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081231/20794b50/attachment.htm From tom.davie at gmail.com Wed Dec 31 11:30:30 2008 From: tom.davie at gmail.com (Thomas Davie) Date: Wed Dec 31 11:22:27 2008 Subject: [Haskell-beginners] about the concatenation on a tree In-Reply-To: <902ff3e80812310702y7b2e4c28g356baffbb8df678@mail.gmail.com> References: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> <902ff3e80812310702y7b2e4c28g356baffbb8df678@mail.gmail.com> Message-ID: On 31 Dec 2008, at 16:02, Max cs wrote: > hi all, not sure if there is someone still working during holiday > like me : ) > > I got a little problem in implementing some operations on tree. > > suppose we have a tree date type defined: > > data Tree a = Leaf a | Branch (Tree a) (Tree a) > > I want to do a concatenation on these tree just like the concat on > list. > Anyone has idea on it? or there are some existing implementation? > > Thank you and Happy New Year! > How would you like to concatenate them? Concatonation on lists is easy because there's only one end point to attach the next list to, on a tree though, there are many leaves to attach things to. Here's a few examples though: Attaching to the right most point on the tree (tree data structure modified to store data in branches not leaves here) data Tree a = Leaf | Branch (Tree a) a (Tree a) concatT :: [Tree a] -> Tree a concatT = foldr1 appendT appendT :: Tree a -> Tree a -> Tree a appendT Leaf t = t appendT (Branch l x r) t = Branch l x (appendT r t) Attaching to *all* the leaves on the tree (same modification to the data structure) concatT :: [Tree a] -> Tree a concatT = foldr1 appendT appendT :: Tree a -> Tree a -> Tree a appendT Leaf t = t appendT (Branch l x r) t = Branch (appendT l t) x (appendT r t) merging a list of trees maintaining them as ordered binary trees concatT :: Ord a => [Tree a] -> Tree a concatT = foldr1 unionT unionT :: Ord a => Tree a -> Tree a -> Tree a unionT t = foldrT insertT t foldrT :: (a -> b -> b) -> b -> Tree a -> b foldrT f z Leaf = z foldrT f z (Branch l x r) = f x (foldrT f (foldrT f z r) l) insertT :: Ord a => a -> Tree a -> Tree a insertT x Leaf = Branch Leaf x Leaf insertT x (Branch l y r) | x <= y = Branch (insertT x l) y r | otherwise = Branch l y (insertT x r) Hope that helps. Bob From raeck at msn.com Wed Dec 31 16:58:48 2008 From: raeck at msn.com (raeck@msn.com) Date: Wed Dec 31 16:50:42 2008 Subject: [Haskell-beginners] bottom case in proof by induction Message-ID: Dear all, Happy New Year! I am learning the Induction Proof over Haskell, I saw some proofs for the equivalence of two functions will have a case called 'bottom' but some of them do no have. What kind of situation we should also include the bottom case to the proof? How about the functions do not have the 'bottom' input such as: foo [] = [] foo (x:xs) = x : (foo xs) thank you, Raeck -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081231/8c98ba3c/attachment.htm From tom.davie at gmail.com Wed Dec 31 17:05:45 2008 From: tom.davie at gmail.com (Thomas Davie) Date: Wed Dec 31 16:57:50 2008 Subject: [Haskell-beginners] Re: about the concatenation on a tree In-Reply-To: <9FADE9BDA1DF47F59D37C761C47B2FF2@hxzhao> References: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> <902ff3e80812310702y7b2e4c28g356baffbb8df678@mail.gmail.com> <2CD4FDAC-247C-4ED5-854E-9FC3CCEF4996@gmail.com> <9FADE9BDA1DF47F59D37C761C47B2FF2@hxzhao> Message-ID: <0E6B9C34-EDDC-415D-B329-526EEBDB1895@gmail.com> On 31 Dec 2008, at 22:38, Max.cs wrote: > Hi Bob, > > Actually I am a fresher in the university and I am doing a > additional exercise for the holiday. > > I think your modification is great, but I am afraid I have to keep > the original forms of the function and data type. I am given the > following code: > >> data Tree a = Leaf a | Branch (Tree a) (Tree a) > >> foldTree :: (a -> b) -> (b -> b -> b) -> Tree a -> b >> foldTree f g (Leaf x) = f x >> foldTree f g (Branch t1 t2) = g (foldTree f g t1) (foldTree f g t2) > > now, what I am asked to do is to complete the following function > concatT using the above foldTree. > >> concatT :: Tree (Tree a) -> Tree a > > the example output of concatT are also given as: > > concatT (Leaf t) = t > concatT (Branch (Leaf t1) (Leaf t2)) = Branch t1 t2 > > I am confused by the type of function concatT and foldTree: > > From the output example, we know, the output should be t (atomic > value) when the input is (Leaf t), and the output will be Branch t1 > t2 (a Branch) when the input is a Branch. But the the definition of > foldTree, the return type of f and g should be the same (both are > b). Am I missing some important point? Any idea on how we can > implement the function concatT ? Sure, but lets go through (most of) the process. We know the function we need has the type Tree (Tree c) -> Tree c. You'll see why I used c as my variable in a minute, and we're given a function with the type (a -> b) -> (b -> b -> b) -> Tree a -> b. Lets try and make that into the type we need. We know the result type must be "Tree c", so lets try replacing all bs with Tree cs: someFunction :: (a -> Tree c) -> (Tree c -> Tree c -> Tree c) -> Tree a -> Tree c We also know that the argument type we want is not a Tree of any values, but actually a Tree of Tree cs, so lets supstitute a for Tree c too: someOtherFunction :: (Tree c -> Tree c) -> (Tree c -> Tree c -> Tree c) -> Tree (Tree c) -> Tree c As we know, in Haskell functions are curried, so this type is the same as (Tree c -> Tree c) -> ((Tree c -> Tree c -> Tree c) -> (Tree (Tree c) -> Tree c)). Note that the last part here is exactly the type we need, so if we provide foldTree with the right two functions, it looks like it's gonna do exactly what we want. Lets look at the rules for foldTree ? it applies f wherever it meets a Leaf, and g wherever it meets a Branch, so lets think about what we want to do in those two situations. In the case of a Leaf, we'd like to replace the leaf with it's value, so the function we're looking for sounds a lot like it does nothing much. In the case of Branches, we'd like to leave them in place, so we probably want to look at the Branch creator function. I'll leave the rest to you :) > Btw, it will be much better if you do not send this email and the > replies to the maillist for this instance, since I think it is not a > very good idea to let my tutor know I am asking question involved in > the exercise. Just let me know if you dont know you want to answer > this question : ) I'm sure your tutor doesn't mind you asking for help, in fact, he's probably the first guy you should go and ask for some help. What he will want to know is exactly how much help you're getting, and how you're doing with the subject matter ? remember, he's trying to teach you, not trying to torture you :). Because of that, I have forwarded this email to the mailing list, you're welcome to use my help or not, depending on how guilty you feel (although unless this is a test, any guilt you feel is entirely in error). Bob From steve at steveklabnik.com Wed Dec 31 22:18:11 2008 From: steve at steveklabnik.com (Steve Klabnik) Date: Wed Dec 31 22:10:02 2008 Subject: [Haskell-beginners] until and Time Message-ID: Hello everyone. I have a quick question about Time. I was talking about Haskell on the Arch Linux forums today, and someone was trying to put together code that would print a series of periods for, say, 5 minutes. I felt like using 'until' would be the most correct way of going about it, but when I tried to do it... import Time makeLater :: ClockTime -> ClockTime makeLater t = addToClockTime (TimeDiff 0 0 0 0 0 5 0) t updateTime :: ClockTime -> ClockTime updateTime t = t main = do start <- getClockTime until ((==) $ makeLater start) (updateTime) start putStrLn "done" Now, updateTime isn't correct. And this wouldn't print any periods. But GHC is giving me errors: $ runhaskell temp.hs temp.hs:11:2: Couldn't match expected type `IO t' against inferred type `ClockTime' In the expression: until ((==) $ makeLater start) (updateTime) start In a 'do' expression: until ((==) $ makeLater start) (updateTime) start In the expression: do start <- getClockTime until ((==) $ makeLater start) (updateTime) start putStrLn "done" I'm not sure where IO t is coming from at all. Am I even on the right track? How would you write this code? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081231/9f9a42d1/attachment-0001.htm From raeck at msn.com Wed Dec 31 22:50:28 2008 From: raeck at msn.com (raeck@msn.com) Date: Wed Dec 31 22:42:25 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] bottom case in proof by induction In-Reply-To: <7ca3f0160812311443v2d9b2560vac98e9ffa79cb4f7@mail.gmail.com> References: <7ca3f0160812311419h882b738r761f427d4c86a5c3@mail.gmail.com> <454A4736C0F147F991F7E56A469E68DC@hxzhao> <7ca3f0160812311443v2d9b2560vac98e9ffa79cb4f7@mail.gmail.com> Message-ID: I am afraid I am still confused. > foo [] = ... > foo (x:xs) = ... > There is an implied: > foo _|_ = _|_ > The right side cannot be anything but _|_. If it could, then that would imply we could solve the halting problem: in a proof, how I could say the right side must be _|_ without defining foo _|_ = _|_ ? and in the case of > bad () = _|_ > bad _|_ = () mean not every function with a _|_ input will issue a _|_ output, so we have to say what result will be issued by a _|_ input in the definitions of the functions if we want to prove the equvalence between them? However, in the case of map f _|_ , I do believe the result will be _|_ since it can not be anything else, but how I could prove this? any clue? ps, the definition of map does not mention anything about _|_ . Thanks Raeck From: Luke Palmer Sent: Wednesday, December 31, 2008 10:43 PM To: Max.cs ; raeck@msn.com Subject: Re: [Haskell-cafe] bottom case in proof by induction On Wed, Dec 31, 2008 at 3:28 PM, Max.cs wrote: thanks Luke, so you mean the _|_ is necessary only when I have defined the pattern _|_ such as foo [] = [] foo _|_ = _|_ foo (x:xs) = x( foo xs ) -- consider non-termination case That is illegal Haskell. But another way of putting that is that whenever you do any pattern matching, eg.: foo [] = ... foo (x:xs) = ... There is an implied: foo _|_ = _|_ The right side cannot be anything but _|_. If it could, then that would imply we could solve the halting problem: halts () = True halts _|_ = False Because _|_ is the denotation of a program which never halts. To do it a bit more domain-theoretically, I'll first cite the result that every function has a fixed point. That is, for every f, there is a function fix f, where fix f = f (fix f). (The fix function is actually available in Haskell from the module Data.Function). Then let's consider this bad function: bad () = _|_ -- you can't write _|_ in Haskell, but "undefined" or "let x = x in x" mean the same thing bad _|_ = () Then what is fix f? Well, it either terminates or it doesn't, right? I.e. fix f = () or fix f = _|_. Taking into account that fix f = f (fix f): If it does: fix f = () = f () = _|_, a contradiction. If it doesn't: fix f = _|_ = f _|_ = (), another contradiction. >From a mathematical perspective, that's why you can't pattern match on _|_. >From an operational perspective, it's just that _|_ means "never terminates", and we can't determine that, because we would try to run it "until it doesn't terminate", which is meaningless... Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20090101/51738186/attachment.htm From daniel.is.fischer at web.de Wed Dec 31 22:54:44 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Dec 31 22:44:08 2008 Subject: [Haskell-beginners] until and Time In-Reply-To: References: Message-ID: <200901010454.44854.daniel.is.fischer@web.de> Am Donnerstag, 1. Januar 2009 04:18 schrieb Steve Klabnik: > Hello everyone. I have a quick question about Time. > > I was talking about Haskell on the Arch Linux forums today, and someone was > trying to put together code that would print a series of periods for, say, > 5 minutes. I felt like using 'until' would be the most correct way of going > about it, but when I tried to do it... > > > import Time > > makeLater :: ClockTime -> ClockTime > makeLater t = addToClockTime (TimeDiff 0 0 0 0 0 5 0) t > > updateTime :: ClockTime -> ClockTime > updateTime t = t > > main = do > start <- getClockTime > until ((==) $ makeLater start) (updateTime) start > putStrLn "done" > > Now, updateTime isn't correct. And this wouldn't print any periods. But GHC > is giving me errors: > > $ runhaskell temp.hs > > temp.hs:11:2: > Couldn't match expected type `IO t' > against inferred type `ClockTime' > In the expression: > until ((==) $ makeLater start) (updateTime) start > In a 'do' expression: > until ((==) $ makeLater start) (updateTime) start > In the expression: > do start <- getClockTime > until ((==) $ makeLater start) (updateTime) start > putStrLn "done" > > I'm not sure where IO t is coming from at all. Am I even on the right > track? How would you write this code? Since it appears as a statement in the main do-block, ghc expects "until ..." to have type IO t. But as Prelude> :t until until :: (a -> Bool) -> (a -> a) -> a -> a until ((==) $ makeLater start) (updateTime) start actually has type ClockTime, so can't appear as a statement in a do-block, that's what ghc tells you. Since you want a timeout, which involves IO, you must do something in IO. You can define a general control structure (I'm sure that is already defined somewhere, but I can't be bothered to hoogle it now) untilM :: (Monad m) => (a -> m Bool) -> (a -> m a) -> a -> m a untilM test action value = do stop <- test value if stop then return value else do newval <- action value untilM test action newval and then isLaterThan :: ClockTime -> IO Bool isLaterThan end = do now <- getClockTime return (end < now) main = do start <- getClockTime let end = addToClockTime (TimeDiff 0 0 0 0 0 5 0) start untilM (\_ -> isLaterThan end) (\_ -> putChar '.') () putStr "\n" From daniel.is.fischer at web.de Wed Dec 31 23:15:01 2008 From: daniel.is.fischer at web.de (Daniel Fischer) Date: Wed Dec 31 23:04:38 2008 Subject: [Haskell-beginners] Re: [Haskell-cafe] bottom case in proof by induction In-Reply-To: References: <7ca3f0160812311443v2d9b2560vac98e9ffa79cb4f7@mail.gmail.com> Message-ID: <200901010515.01975.daniel.is.fischer@web.de> Am Donnerstag, 1. Januar 2009 04:50 schrieb raeck@msn.com: > I am afraid I am still confused. > > > foo [] = ... > > foo (x:xs) = ... > > There is an implied: > > foo _|_ = _|_ > > The right side cannot be anything but _|_. If it could, then that would > > imply we could solve the halting problem: > > in a proof, how I could say the right side must be _|_ without defining foo > _|_ = _|_ ? and in the case of Because _|_ is matched against a refutable pattern ([], in this case), so when foo is called with argument _|_, the runtime tries to match it against []. For that, it must reduce it far enough to know its top level constructor, which by definition of _|_ isn't possible, so the pattern match won't terminate, hence foo _|_ is a nonterminating computation, i.e. _|_. > > > bad () = _|_ > > bad _|_ = () You can't do that. You can only pattern-match against patterns, which _|_ isn't. > > mean not every function with a _|_ input will issue a _|_ output, so we > have to say what result will be issued by a _|_ input in the definitions of > the functions if we want to prove the equvalence between them? If you match against an irrefutable pattern (variable, wildcard or ~pattern), the matching succeeds without evaluating the argument, so then you can have functions which return a terminating value for nonterminating arguments: lazyMap ~(x:xs) = [[],[x],xs] *LazyTest> lazyMap undefined [[],[*** Exception: Prelude.undefined *LazyTest> lazyMap [] [[],[*** Exception: PrintPer.hs:28:0-28: Irrefutable pattern failed for pattern (x : xs) *LazyTest> take 1 $ lazyMap undefined [[]] > > However, in the case of map f _|_ , I do believe the result will be _|_ > since it can not be anything else, but how I could prove this? any clue? > > ps, the definition of map does not mention anything about _|_ . As above, evaluation of map f _|_ tries to match _|_ against [], which doesn't terminate. > > Thanks > Raeck > From ryani.spam at gmail.com Mon Dec 29 04:48:50 2008 From: ryani.spam at gmail.com (Ryan Ingram) Date: Sat Jan 3 21:15:33 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function In-Reply-To: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> Message-ID: <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> On Sun, Dec 28, 2008 at 10:13 PM, David Menendez wrote: > 2008/12/29 Raeck chiu : >> It seems to be very difficult to change the number of Male or Female if a >> concrete data structure is not used. Is it possible change the number of Male in classA >> when represent classA using function? > > Here's the simplest way: > > update k v map = \k' -> if k' == k then v else map k' > > Note that it requires an Eq instance for Sex. > > let classA' = update Male 150 classA > in (classA' Male, classA' Female) > = > (150,200) Of course this version of update leaks crazy amounts of memory: > let bigmap = iterate (update Male 150) classA !! 100000 > bigmap Male "bigmap" leaves a huge chain of thunks pointing at each other, which can never be freed. Using functions is mathematically more elegant than some concrete data structure (which might require Eq or Ord or other constraints, and have multiple observable representations for the same map, or have maps that don't include every element). However, "generic maps" have been improving a lot recently, especially with data families in the new GHC. You use an abstract type (k :-> v) to represent the map; this type is semantically equivalent to (k -> v) via some observation function for generic maps, but has a compact representation. For example: > class MapKey k where > data k :-> v > newMap :: (k -> v) -> (k :-> v) > fetch :: (k :-> v) -> (k -> v) > update :: (k,v) -> (k :-> v) -> (k :-> v) > empty :: v -> (k :-> v) > empty = newMap (const v) > instance MapKey Bool where > data Bool :-> v = BoolMap v v > newMap f = BoolMap (f False) (f True) > fetch (Boolmap t f) v = if v then t else f > update (True, t) (BoolMap _ f) = Boolmap t f > update (False, f) (BoolMap t _) = Boolmap t f "fetch" converts this representation of a total function over k, into an actual function. The representation of k :-> v might vary depending on k; Int might use IntMap, (k1,k2) can compose maps: > instance (MapKey k1, MapKey k2) => MapKey (k1,k2) where > newtype (k1,k2) :-> v = PairMap (k1 :-> (k2 :-> v)) > ... > instance (MapKey k1, MapKey k2) => MapKey (Either k1 k2) where > data (Either k1 k2) :-> v = EitherMap (k1 :-> v) (k2 :-> v) > ... This gives you the same benefits as the function approach but without the terrible performance issues. You do need to write instances for your types, though, although most can be easily derived from the instances for pairs, Either, and Integer. See http://www.haskell.org/haskellwiki/GHC/Indexed_types for more. -- ryan From ryani.spam at gmail.com Mon Dec 29 18:15:38 2008 From: ryani.spam at gmail.com (Ryan Ingram) Date: Sat Jan 3 21:16:03 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function In-Reply-To: References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> Message-ID: <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> On Mon, Dec 29, 2008 at 4:29 AM, wrote: > Would you please give me a complete example of code that I could have more > information > on the idea? Sure, I put up an example at http://ryani.freeshell.org/haskell/gmap.hs class MapKey k where data (:->) k :: * -> * newMap :: (k -> v) -> (k :-> v) fetch :: (k :-> v) -> (k -> v) update :: k -> (v -> v) -> (k :-> v) -> (k :-> v) assign :: k -> v -> (k :-> v) -> (k :-> v) assign k v m = update k (const v) m empty :: v -> (k :-> v) empty = newMap . const with instances & associated data types: instance MapKey () where -- A single value newtype () :-> v = UMap v instance MapKey Bool where -- A value for False and True data Bool :-> v = BMap v v instance (MapKey k1, MapKey k2) => MapKey (k1,k2) where -- A "curried" map newtype (k1,k2) :-> v = PMap (k1 :-> k2 :-> v) instance (MapKey k1, MapKey k2) => MapKey (Either k1 k2) where -- sub-maps for Left k1 and Right k2 data (Either k1 k2 :-> v) = EMap (k1 :-> v) (k2 :-> v) instance MapKey k => MapKey (Maybe k) where -- Now we can build up from existing structures! newtype (Maybe k) :-> v = MaybeM (Either () k :-> v) instance MapKey k => MapKey [k] where -- Value for [] and map for (head:tail) -- -- Note that this includes a recursive ([k] :-> v) map -- in the pair map (k,[k]) :-> v data [k] :-> v = ListM v ((k,[k]) :-> v) instance MapKey Positive where -- We just convert a positive number into -- a list of Bools, then make a map of those newtype Positive :-> v = PosMap ([Bool] :-> v) instance MapKey Integer where -- Now an integer is either negative, zero, or positive. -- So we store a map for negative numbers, a zero value, -- and a map for positive numbers. data Integer :-> v = IntMap (Positive :-> v) v (Positive :-> v) The rest of the class functions are reasonably easy to derive from their type and these data types. -- ryan From ryani.spam at gmail.com Mon Dec 29 04:50:02 2008 From: ryani.spam at gmail.com (Ryan Ingram) Date: Sat Jan 3 21:16:36 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function In-Reply-To: <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> Message-ID: <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> Bonus points if you find the stupid bug in my code :) -- ryan On Mon, Dec 29, 2008 at 1:48 AM, Ryan Ingram wrote: > On Sun, Dec 28, 2008 at 10:13 PM, David Menendez wrote: >> 2008/12/29 Raeck chiu : >>> It seems to be very difficult to change the number of Male or Female if a >>> concrete data structure is not used. Is it possible change the number of Male in classA >>> when represent classA using function? >> >> Here's the simplest way: >> >> update k v map = \k' -> if k' == k then v else map k' >> >> Note that it requires an Eq instance for Sex. >> >> let classA' = update Male 150 classA >> in (classA' Male, classA' Female) >> = >> (150,200) > > Of course this version of update leaks crazy amounts of memory: > >> let bigmap = iterate (update Male 150) classA !! 100000 >> bigmap Male > > "bigmap" leaves a huge chain of thunks pointing at each other, which > can never be freed. > > Using functions is mathematically more elegant than some concrete data > structure (which might require Eq or Ord or other constraints, and > have multiple observable representations for the same map, or have > maps that don't include every element). > > However, "generic maps" have been improving a lot recently, especially > with data families in the new GHC. You use an abstract type (k :-> > v) to represent the map; this type is semantically equivalent to (k -> > v) via some observation function for generic maps, but has a compact > representation. For example: > >> class MapKey k where >> data k :-> v >> newMap :: (k -> v) -> (k :-> v) >> fetch :: (k :-> v) -> (k -> v) >> update :: (k,v) -> (k :-> v) -> (k :-> v) >> empty :: v -> (k :-> v) >> empty = newMap (const v) > >> instance MapKey Bool where >> data Bool :-> v = BoolMap v v >> newMap f = BoolMap (f False) (f True) >> fetch (Boolmap t f) v = if v then t else f >> update (True, t) (BoolMap _ f) = Boolmap t f >> update (False, f) (BoolMap t _) = Boolmap t f > > "fetch" converts this representation of a total function over k, into > an actual function. The representation of k :-> v might vary > depending on k; Int might use IntMap, (k1,k2) can compose maps: > >> instance (MapKey k1, MapKey k2) => MapKey (k1,k2) where >> newtype (k1,k2) :-> v = PairMap (k1 :-> (k2 :-> v)) >> ... > >> instance (MapKey k1, MapKey k2) => MapKey (Either k1 k2) where >> data (Either k1 k2) :-> v = EitherMap (k1 :-> v) (k2 :-> v) >> ... > > This gives you the same benefits as the function approach but without > the terrible performance issues. You do need to write instances for > your types, though, although most can be easily derived from the > instances for pairs, Either, and Integer. > > See http://www.haskell.org/haskellwiki/GHC/Indexed_types for more. > > -- ryan > From robgreayer at yahoo.com Tue Dec 30 12:45:36 2008 From: robgreayer at yahoo.com (Robert Greayer) Date: Sat Jan 3 21:17:02 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] Enum and Bounded in generic type References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> Message-ID: <755388.25786.qm@web65703.mail.ac4.yahoo.com> Raeck said: > Hi, how can I make the following code work? (show all the possible values of a type 'a') >> showAll :: (Eq a, Bounded a, Enum a) => a -> [a] >> showAll a = [minBound..maxBound]::[a] What you are really looking for, I think, is a polymorphic value of type [a], where a is some enumerable, bounded type. allValues :: (Enum a, Bounded a) => [a] allValues = [minBound .. maxBound] You can omit the type signature, but then you'll run into the monomorphism restriction (which you'll can turn off with, e.g. -XNoMonomorphismRestriction) From max.cs.2009 at googlemail.com Wed Dec 31 09:59:24 2008 From: max.cs.2009 at googlemail.com (Max cs) Date: Sat Jan 3 21:19:23 2009 Subject: [Haskell-beginners] about the concatenation on a tree Message-ID: <902ff3e80812310659j2ee7949du7a54bcf5de7c0139@mail.gmail.com> hi all, not sure if there is someone still working during holiday like me : ) I got a little problem in implementing some operations on tree. suppose we have a tree date type defined: data Tree a = Leaf a | Branch (Tree a) (Tree a) I want to do a concatenation on these tree just like the concat on list. Anyone has idea on it? or there are some existing implementation? Thank you and Happy New Year! regards, Max -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081231/8de41a30/attachment.htm From martijn at van.steenbergen.nl Wed Dec 31 20:16:39 2008 From: martijn at van.steenbergen.nl (Martijn van Steenbergen) Date: Sat Jan 3 21:19:56 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] bottom case in proof by induction In-Reply-To: <7ca3f0160812311419h882b738r761f427d4c86a5c3@mail.gmail.com> References: <7ca3f0160812311419h882b738r761f427d4c86a5c3@mail.gmail.com> Message-ID: <495C1977.8070303@van.steenbergen.nl> Luke Palmer wrote: > First, by simple definition, id _|_ = _|_. Now let's consider foo _|_. > The Haskell semantics say that pattern matching on _|_ yields _|_, so > foo _|_ = _|_. So they are equivalent on _|_ also. Thus foo and id are > exactly the same function. Would it in general also be interesting to look at foo == id for input (_|_:xs) and all other possible positions and combinations of positions for bottom? I wonder how many cases you need to take into consideration to have covered every possible situation. Martijn. From lrpalmer at gmail.com Mon Dec 29 20:28:46 2008 From: lrpalmer at gmail.com (Luke Palmer) Date: Sat Jan 3 21:20:26 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] 'Iterating a data type' In-Reply-To: References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> Message-ID: <7ca3f0160812291728t2fedb2a9gc207a7dcfd4a8450@mail.gmail.com> On Mon, Dec 29, 2008 at 6:24 PM, wrote: > Are there anyway to express the "iterating" of a user-defined data type in > Haskell? > > For example, in > > data Shape = Square | Circle | Triangle >> > > how can I 'iterate' them and apply them all to the same function without > indicating them explicitly? > such as [func Square, func Circle, func Triangle]. > Can I use a form similar to the following case in a list instead: > > Numbers = [1,2,3,4,5] >> > > [func x | x <- Numbers ] >> > > Actually what I want is to obtain all the possible values of a data type > (Shape). For "enum" style data, where all the constructors have no arguments, you can do deriving (Bounded, Enum), so: data Shape = Square | Circle | Triangle deriving (Bounded,Enum) Then: numbers = [minBound..maxBound] :: [Shape] Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081229/a5358a1f/attachment.htm From lrpalmer at gmail.com Wed Dec 31 17:19:26 2008 From: lrpalmer at gmail.com (Luke Palmer) Date: Sat Jan 3 21:20:55 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] bottom case in proof by induction In-Reply-To: References: Message-ID: <7ca3f0160812311419h882b738r761f427d4c86a5c3@mail.gmail.com> 2008/12/31 > Dear all, > > Happy New Year! > > I am learning the Induction Proof over Haskell, I saw some proofs for the > equivalence of two functions will have a case called 'bottom' but some of > them do no have. What kind of situation we should also include the bottom > case to the proof? How about the functions do not have the 'bottom' input > such as: > > foo [] = [] > foo (x:xs) = x : (foo xs) > Okay, I'm not sure what you mean by bottom. You could either mean the base case, or you could mean bottom -- non-terminating inputs -- as in domain theory. Let's say you wanted to see if foo is equivalent to id. id x = x We can do it without considering nontermination, by induction on the structure of the argument: First, the *base case*: empty lists. foo [] = [] id [] = [] Just by looking at the definitions of each. Now the inductive case. Assume that foo xs = id xs, and show that foo (x:xs) = id (x:xs), for all x (but a fixed xs). foo (x:xs) = x : foo xs foo xs = id xs by our the induction hypothesis, so foo (x:xs) = x : id xs = x : xs And then just by the definition of id: id (x:xs) = x : xs And we're done. Now, maybe you meant bottom as in nontermination. In this case, we have to prove that they do the same thing when given _|_ also. This requires a deeper understanding of the semantics of the language, but can be done here. First, by simple definition, id _|_ = _|_. Now let's consider foo _|_. The Haskell semantics say that pattern matching on _|_ yields _|_, so foo _|_ = _|_. So they are equivalent on _|_ also. Thus foo and id are exactly the same function. See http://en.wikibooks.org/wiki/Haskell/Denotational_semantics for more about _|_. Happy mathhacking, Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://www.haskell.org/pipermail/beginners/attachments/20081231/71a112a0/attachment.htm From jonathanccast at fastmail.fm Wed Dec 31 23:08:57 2008 From: jonathanccast at fastmail.fm (Jonathan Cast) Date: Sat Jan 3 21:21:26 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] bottom case in proof by induction In-Reply-To: References: <7ca3f0160812311419h882b738r761f427d4c86a5c3@mail.gmail.com> <454A4736C0F147F991F7E56A469E68DC@hxzhao> <7ca3f0160812311443v2d9b2560vac98e9ffa79cb4f7@mail.gmail.com> Message-ID: <1230782941.6019.12.camel@jonathans-macbook> On Thu, 2009-01-01 at 03:50 +0000, raeck@msn.com wrote: > I am afraid I am still confused. > > > foo [] = ... > > foo (x:xs) = ... > > There is an implied: > > foo _|_ = _|_ > > The right side cannot be anything but _|_. If it could, then that > would imply we could solve the halting problem: > > in a proof, how I could say the right side must be _|_ without > defining foo _|_ = _|_ ? This definition is taken care of for you by the definition of Haskell pattern matching. If the first equation for a function has a pattern other than * a variable or * a lazy pattern (~p) for a given argument, then supplying _|_ for that argument /must/ (if the application is total) return _|_. By rule. (We say the pattern is strict, in this case). > and in the case of > > > bad () = _|_ > > bad _|_ = () Note that these equations (which are not in the right form for the Haskell equations that define Hasekll functions) aren't satisfied by any Haskell function! > mean not every function with a _|_ input will issue a _|_ output, True --- but we can say a couple of things: * For all Haskell functions f, if f _|_ is an application of a constructor C, then f x is an application of C (to some value), for all x. [1] * For all Haskell functions f, if f _|_ is a lambda expression, then f x is a lambda expression, for all x. The only other possibility for f _|_ is _|_. (Do you see why bad above is impossible?) > so we have to say what result will be issued by a _|_ input in the > definitions of the functions if we want to prove the equvalence > between them? You have to deduce what the value at _|_ will be. > However, in the case of map f _|_ , I do believe the result will be > _|_ since it can not be anything else, but how I could prove this? any > clue? Appeal to the semantics of Haskell pattern matching. If you like, you can de-sugar the definition of map a little, to get map = \ f xn -> case xn of [] -> [] x:xn0 -> f x : map f xn0 And then you know that case _|_ of [] -> ... ... = _|_ whatever you fill in for the ellipses. (Do you see why this *must* be part of the language definition?) > ps, the definition of map does not mention anything about _|_ . The behavior of map f _|_ is fixed by the definition of Haskell pattern matching. jcc From derek.a.elkins at gmail.com Tue Dec 30 12:22:34 2008 From: derek.a.elkins at gmail.com (Derek Elkins) Date: Sat Jan 3 21:22:57 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] Enum and Bounded in generic type In-Reply-To: References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> <2f9b2d30812290150j49f48dbav1a063915453e7ad9@mail.gmail.com> <2f9b2d30812291515k7160c070x4427c0dd943ab1d3@mail.gmail.com> Message-ID: <1230657754.31199.1.camel@derek-laptop> On Tue, 2008-12-30 at 17:12 +0000, raeck@msn.com wrote: > Hi, how can I make the following code work? (show all the possible values of > a type 'a') > ? > > showAll :: (Eq a, Bounded a, Enum a) => a -> [a] > > showAll a = [minBound..maxBound]::[a] The bottom 'a' has nothing to do with the 'a' in the type signature. Your code is equivalent to ? > > showAll :: (Eq a, Bounded a, Enum a) => a -> [a] > > showAll a = [minBound..maxBound]::[b] Which is not type correct as [minBound..maxBound] :: (Bounded a, Enum a) => [a] You don't need that type annotation (or the type signature for that matter), so just omit it. From dave at zednenem.com Mon Dec 29 01:13:54 2008 From: dave at zednenem.com (David Menendez) Date: Sat Jan 3 21:23:36 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function In-Reply-To: References: Message-ID: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> 2008/12/29 Raeck chiu : > People sometime will try to represent a quantity-regard-only data structure > (such a order-regadless List) using functions instead of ta concrete data > structure (like the haskell build-in []), any particular reason for this? > > For example, >> data Sex = Male | Female >> classA :: Sex -> Int >> classA Male = 100 >> classA Female = 200 > > when I should prefer the above solution instead of using a concrete data > structure such as [] to represent the classA members? One important difference between Sex -> Int and [(Sex,Int)] is that the first guarantees exactly one Int per Sex and has no underlying order. (That is, [(Male,100),(Female,200)] and [(Female,200),(Male,100)] are distinct lists but represent the same map.) > It seems to be very difficult to change the number of Male or Female if a > concrete data structure is not used. Is it possible change the number of Male in classA > when represent classA using function? Here's the simplest way: update k v map = \k' -> if k' == k then v else map k' Note that it requires an Eq instance for Sex. let classA' = update Male 150 classA in (classA' Male, classA' Female) = (150,200) -- Dave Menendez From dave at zednenem.com Mon Dec 29 13:26:12 2008 From: dave at zednenem.com (David Menendez) Date: Sat Jan 3 21:23:58 2009 Subject: [Haskell-beginners] Re: [Haskell-cafe] represent data sturcture using function In-Reply-To: <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> References: <49a77b7a0812282213vc67a4d7x673859960fbfc0a3@mail.gmail.com> <2f9b2d30812290148l19b3bd4fg4e5779ccde13eaee@mail.gmail.com> Message-ID: <49a77b7a0812291026m5ae53864h56bc0c8f4c5315b6@mail.gmail.com> On Mon, Dec 29, 2008 at 4:48 AM, Ryan Ingram wrote: > On Sun, Dec 28, 2008 at 10:13 PM, David Menendez wrote: >> Here's the simplest way: >> >> update k v map = \k' -> if k' == k then v else map k' > Of course this version of update leaks crazy amounts of memory: > >> let bigmap = iterate (update Male 150) classA !! 100000 >> bigmap Male > > "bigmap" leaves a huge chain of thunks pointing at each other, which > can never be freed. Sure. It's slow, too. If you want a map that you can update, you're usually much better off with a concrete data structure. -- Dave Menendez