From dennis.raddle at gmail.com Sun May 1 00:16:41 2016 From: dennis.raddle at gmail.com (Dennis Raddle) Date: Sat, 30 Apr 2016 17:16:41 -0700 Subject: [Haskell-beginners] audio generation In-Reply-To: <878tzvrn84.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> References: <878tzvrn84.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: On Sat, Apr 30, 2016 at 11:00 AM, Daniel Bergey wrote: > The entire topic of space use in Haskell is not simple, but the part you > need here may be. As long as GHC can tell that values already written > to disk may be garbage collected, memory use is quite reasonable. > > For example, here's a short program that prints a long-ish list: > > xs :: [Double] > xs = map cos [1..1e7] > > main :: IO () > main = traverse_ print $ map sin xs > > Thanks. I'll see if this works for me. My question right now is, what is traverse_print? Is that the same as main = traverse print . map sin $ xs ? I'm guessing IO is traversable and for some reason you don't want to use mapM. D -------------- next part -------------- An HTML attachment was scrubbed... URL: From bergey at alum.mit.edu Sun May 1 02:08:50 2016 From: bergey at alum.mit.edu (Daniel Bergey) Date: Sat, 30 Apr 2016 22:08:50 -0400 Subject: [Haskell-beginners] audio generation In-Reply-To: References: <878tzvrn84.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <8737q2sf65.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> On 2016-04-30 at 20:16, Dennis Raddle wrote: > main :: IO () > main = traverse_ print $ map sin xs > > Thanks. I'll see if this works for me. My question right now is, what is traverse_print? > Is that the same as > > main = traverse print . map sin $ xs > > ? > > I'm guessing IO is traversable and for some reason you don't want to use mapM. traverse_ is in Data.Foldable [1] You're right that it's closely related to `traverse` and `mapM`. I generally prefer `traverse` and `traverse_` to `mapM` and `mapM_` because they only require Applicative, not Monad. So they work in more cases, and generic code can be more generic. The versions with the _ give back `f ()` instead of `f b` - in this case, we get `IO ()` instead of `IO [()]`. If you try with `traverse, the program won't typecheck, because main needs to have type `IO ()`. bergey Footnotes: [1] http://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Foldable.html#v:traverse_ From silent.leaf0 at gmail.com Sun May 1 09:56:11 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Sun, 1 May 2016 11:56:11 +0200 Subject: [Haskell-beginners] Trying to prove Applicative is superclass of Functor, etc In-Reply-To: <8760uyssln.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> References: <87inz0sh2f.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> <8760uyssln.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: I see, thanks for all this information! Here must be the answer of why, possibly, liftM is written in terms of monads and not of fmap. Yes I was saying "not heavywork" at the time I didn't know you could create an instance of Monad and use its methods to fill the superclasses even though intuitively it looked like the Monad instance couldn't be accepted if the superclass weren't already. Does anyone have an explanation for this? Le samedi 30 avril 2016, Daniel Bergey a ?crit : > On 2016-04-30 at 15:14, Silent Leaf wrote: >> I think I got what exactly was the change of ghc 7.10. basically it only adds a >> constraint Applicative on the Monad class, and same with >> Functor/Applicative. > > 7.10 adds the constraint on the Monad class. Prior to 7.10, both Monads > and Applicatives already needed to be Functors. > >> Otherwise it's forcing the programmer to do even more possibly-useless >> work (we don't always need applicative and functors for every use of a >> new monad, do we?) > > The practical advantage comes when I want to write some code that is > generic over Monads. If I can't assume that every Monad is Applicative, > my choices are: > > 1) Write (Applicative m, Monad m) =>, and not work for those Monads > 2) Write `ap` everywhere I mean <*>, which for some instances is less > efficient > 3) Write two versions, one like (1) and one like (2) > > None of these are very appealing, and orphan instances are a pain, so > there's already strong social pressure that any Monad instance on > Hackage should have the corresponding Applicative instance defined. > >> in short i think if they wanted mathematical correctness they should >> have added automatic instanciation of superclasses, with possibility >> to override the default definitions, like they do so with some >> superfluous methods. > > Several ways of automatically defining superclasses were discussed as > part of the AMP changes. Maybe we'll get one in some future GHC. I > don't know the details, but some of the discussion: > > https://ghc.haskell.org/trac/ghc/wiki/IntrinsicSuperclasses > https://ghc.haskell.org/trac/ghc/wiki/DefaultSuperclassInstances > https://ghc.haskell.org/trac/ghc/wiki/InstanceTemplates > >> Not that write functors or applicative functor instances is actually heavywork, of >> course, thankfully. > > You know that if the instances are all in the same module, you can use > the Monad functions, right? So the extra work is just pasting in: > > instance Functor m where > fmap = liftM > > instance Applicative m where > pure = return > (<*>) = ap > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy at n-heptane.com Mon May 2 04:59:16 2016 From: jeremy at n-heptane.com (Jeremy Shaw) Date: Sun, 1 May 2016 23:59:16 -0500 Subject: [Haskell-beginners] audio generation In-Reply-To: References: Message-ID: You might consider using the pipes library: http://hackage.haskell.org/package/pipes-4.1.8/docs/Pipes-Tutorial.html The pipes library will allow you to generate audio and write it to disk with out having to worry if you are going to suck up all the RAM accidentally. It should also help you decompose your pipeline into smaller pieces. For example, you would like to be able to decompose your code into things like: 1. the code that generates the audio 2. the code that converts the audio into a format like wav/aiff/etc 3. the code that writes binary data to disk And then simply glue those pieces together, while feeling secure that you don't create a space leak in the process. It will also allow you to use StateT or IO (or anything other type with a Monad instance) if you need to. The pipes library is not trivial to learn. But it is well designed. Without using the pipes library you have two options: 1. understand how laziness works and then be very careful to make sure you never accidentally hold onto data too long and cause a space leak. 2. use strict IO functions and write code that generates the output in little chunks at a time. The concept is, perhaps, easy to understand. But as your code base grows, the code will become harder to understand and to modify. Assuming you chose to use the pipes library, you then also need to decide what size chunks you want to work with. You could write all your code to work with one sample at a time. That is to say, you could always yield/await example one sample. But for better performance you might decide to use buffers and work with 32, 64, 512, etc samples at a time. That can provide better performance. However, it could also make it harder to deal with modulating parameters. For example, if you are doing a filter sweep, you might only be able to change the cutoff frequency at the beginning of each buffer. So the sweep would not be as smooth as it would be if you yielded/await single samples. Though, in practice, I think you are pretty unlikely to notice the difference for reasonably sized buffer sizes. - jeremy On Fri, Apr 29, 2016 at 10:58 PM, Dennis Raddle wrote: > I'm writing a program that will use functions to generate audio. The Haskell > code will write the audio samples to disk---no need for real time playback. > I see some useful libraries for writing audio files. > > My question concerns efficiency when generating several million to 20 > million samples (or even many times more than that if I use high-resolution > sampling rates). They can be generated one at a time in sequence, so there's > no need to occupy a lot of memory or postpone thunk evaluation. I'm going to > need efficient disk writing. Note that I may need some pseudorandom numbers > in my calculations, so I might want to calculate samples by state monadic > computations to carry the generator state. What is my general strategy going > to be for memory and time efficiency? I am pretty confused by Haskell > "strictness" and normal head form and all that, which often doesn't seem to > be very strict. Or bang patterns, etc. Is it going to be simple to > understand what I need? > > Dennis > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From mdibaiee at aol.com Mon May 2 18:55:20 2016 From: mdibaiee at aol.com (Mahdi) Date: Mon, 2 May 2016 23:25:20 +0430 Subject: [Haskell-beginners] CAF taking all the memory Message-ID: <16B1C1BB-4565-43E3-A83A-355F7FDD8A3A@aol.com> Hello there, I?m pretty new to Haskell and I?m trying to write a Neural Network in Haskell for educational purposes. So, I have my neural network working, it can learn XOR in 500 iterations, but the thing is, if I increase the iterations to something like 5 milion times, the process just drains my RAM until either it?s killed or the OS drowns. Here is the code: [0] I searched online and tried to get information on why this is happening, I profiled the memory usage and found that the memory is taken by CAF, searching online, it seems like an optimization done by compiler to reduce runtime computations. Here is the profile: [1] I searched online on how to prevent this from happening, couldn?t find anything helpful. I found this [2] and tried the workaround, but it didn?t work. Is there any way to solve this problem? Because when I?m moving to more complex problems, I have to train with much more iterations, and it just doesn?t work. [0] https://github.com/mdibaiee/biscuit/blob/master/src/examples/xor.hs [1] https://gist.github.com/mdibaiee/95878469a80f1c448b8cf0762178720e [2] http://stackoverflow.com/questions/6090932/how-to-make-a-caf-not-a-caf-in-haskell Thank you, ? Mahdi From dennis.raddle at gmail.com Mon May 2 22:32:21 2016 From: dennis.raddle at gmail.com (Dennis Raddle) Date: Mon, 2 May 2016 15:32:21 -0700 Subject: [Haskell-beginners] audio generation In-Reply-To: References: Message-ID: On Sun, May 1, 2016 at 9:59 PM, Jeremy Shaw wrote: > You might consider using the pipes library: > > http://hackage.haskell.org/package/pipes-4.1.8/docs/Pipes-Tutorial.html > > The pipes library will allow you to generate audio and write it to > disk with out having to worry if you are going to suck up all the RAM > accidentally. > > It should also help you decompose your pipeline into smaller pieces. > For example, you would like to be able to decompose your code into > things like: > > 1. the code that generates the audio > 2. the code that converts the audio into a format like wav/aiff/etc > 3. the code that writes binary data to disk > > And then simply glue those pieces together, while feeling secure that > you don't create a space leak in the process. > > It will also allow you to use StateT or IO (or anything other type > with a Monad instance) if you need to. > > The pipes library is not trivial to learn. But it is well designed. > > Without using the pipes library you have two options: > > 1. understand how laziness works and then be very careful to make > sure you never accidentally hold onto data too long and cause a space > leak. > > 2. use strict IO functions and write code that generates the output > in little chunks at a time. The concept is, perhaps, easy to > understand. But as your code base grows, the code will become harder > to understand and to modify. > Thanks, Jeremy. At this time the code is experimental and may never go anywhere after the initial experiments, so if your option #2 is the easiest to get going, that would be my choice. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From newhoggy at gmail.com Mon May 2 22:49:38 2016 From: newhoggy at gmail.com (John Ky) Date: Mon, 02 May 2016 22:49:38 +0000 Subject: [Haskell-beginners] ByteString unfold that can fail Message-ID: Hello, Does anyone know of anything like Data.ByteString.unfoldr, except that it can fail with a return value? Cheers, -John ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon.jakobi at googlemail.com Mon May 2 23:34:27 2016 From: simon.jakobi at googlemail.com (Simon Jakobi) Date: Tue, 3 May 2016 01:34:27 +0200 Subject: [Haskell-beginners] ByteString unfold that can fail In-Reply-To: References: Message-ID: Hi John, what's the exact type you're looking for? Does hoogle give any useful results for it? Cheers, Simon From ollie at ocharles.org.uk Tue May 3 08:29:10 2016 From: ollie at ocharles.org.uk (Oliver Charles) Date: Tue, 03 May 2016 08:29:10 +0000 Subject: [Haskell-beginners] ByteString unfold that can fail In-Reply-To: References: Message-ID: If there is an unfoldM like function then that might do the job, with Maybe or MaybeT m as your choice of monad. Ollie On Mon, 2 May 2016, 11:49 p.m. John Ky, wrote: > Hello, > > Does anyone know of anything like Data.ByteString.unfoldr, except that it > can fail with a return value? > > Cheers, > > -John > ? > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben at smart-cactus.org Tue May 3 10:06:38 2016 From: ben at smart-cactus.org (Ben Gamari) Date: Tue, 03 May 2016 12:06:38 +0200 Subject: [Haskell-beginners] CAF taking all the memory In-Reply-To: <16B1C1BB-4565-43E3-A83A-355F7FDD8A3A@aol.com> References: <16B1C1BB-4565-43E3-A83A-355F7FDD8A3A@aol.com> Message-ID: <87h9ef78wh.fsf@smart-cactus.org> Mahdi writes: > Hello there, > Hi! > I?m pretty new to Haskell and I?m trying to write a Neural Network in > Haskell for educational purposes. > > So, I have my neural network working, it can learn XOR in 500 > iterations, but the thing is, if I increase the iterations to > something like 5 milion times, the process just drains my RAM until > either it?s killed or the OS drowns. Here is the code: [0] > > I searched online and tried to get information on why this is > happening, I profiled the memory usage and found that the memory is > taken by CAF, searching online, > Great! The next question you should then ask is "which CAF"? A CAF is simply a top-level "constant" in your program. Indeed it sounds like you have not defined any cost-centers, which means that GHC will attribute the entire cost of your program to the ambiguous cost-center "CAF" (which in this case really just means "the whole program"). As discussed in the users guide [1] one way to define cost-centers within your program is to manually annotate expressions with SCC pragmas. However, in this case we simply want to let GHC do this for us, for which we can use the `-fprof-auto -fprof-cafs` flags (which automatically annotate top-level definitions and CAFs with cost-centers), $ ghc -O examples/xor.hs -fprof-auto -fprof-cafs Now your program should give a much more useful profile (run having set the iteration count to 50000), $ time examples/xor +RTS -p [[0.99548584],[4.5138146e-3],[0.9954874],[4.513808e-3]] real 0m4.019s user 0m0.004s sys 0m4.013s $ cat xor.prof Tue May 3 11:15 2016 Time and Allocation Profiling Report (Final) xor +RTS -p -RTS total time = 1.11 secs (1107 ticks @ 1000 us, 1 processor) total alloc = 1,984,202,600 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc matrixMap Utils.Math 21.4 26.8 matadd Utils.Math 20.8 22.7 matmul.\ Utils.Math 10.4 16.0 dot Utils.Math 7.1 13.4 column Utils.Math 7.0 2.9 dot.\ Utils.Math 6.9 1.9 rowPairs Utils.Math 5.8 6.5 sigmoid' NN 4.7 0.8 train.helper Main 4.0 1.3 sigmoid NN 3.3 0.8 matmul Utils.Math 2.2 2.0 hadamard Utils.Math 1.8 2.1 columns Utils.Math 1.2 1.3 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 79 0 0.0 0.0 100.0 100.0 [snip] CAF:main3 Main 143 0 0.0 0.0 100.0 100.0 (...) Main 162 1 0.0 0.0 100.0 100.0 train Main 163 1 0.0 0.0 100.0 100.0 train.helper Main 164 50001 4.0 1.3 100.0 100.0 train.helper.hweights Main 258 50001 0.5 0.0 0.5 0.0 train.helper.oweights Main 235 50001 0.4 0.0 0.4 0.0 train.helper.oback Main 207 50000 0.3 0.1 19.0 20.9 backward' NN 208 50000 0.3 0.6 18.7 20.8 [snip] So, here we see that costs are actually spread throughout the program. Without diving any deeper into this particular program it's hard to give more guidance however I will say that your lazy list Matrix representation is very rarely the right choice for even toy linear algebra problems. First, consider the fact that even just a list cons constructor requires three words (an info table pointer, a pointer to payload, and a pointer to tail) plus the size of the payload (which in the case of an evaluated `Float` is 2 words: one info table pointer and the floating point value itself). So, a list of n *evaluated* `Float`s (which would require only 4*n bytes if packed densely) will require 40*n bytes if represented as a lazy list. Then, consider the fact that indexing into a lazy list is an O(n) operation: this means that your `Math.column` operation on an n x m matrix may be O(n*m). Even worse, `Math.columns`, as used by `Math.matmul` is O(n * m!). Finally, consider the fact that whenever you "construct" a lazy list you aren't actually performing any computation: you are actually constructing a single thunk which represents the entire result; however, if you then go to index into the middle of that list you will end up constructing n cons cells and a thunk for the payload of each. In the case of primitive linear algebra operations the cost of constructing this payload thunk can be greater than simply computing the result. For these reasons I wouldn't recommend that lazy lists are used in this way. If you have a dense matrix use an array (probably even unboxed; see, for instance, the `array`, `vector`, and `repa` libraries); if you have a sparse matrix then use an appropriate sparse representation (although sadly good sparse linear algebra tools are hard to come by in Haskell) Not only will the result be significantly more efficient in space and time but the runtime behavior of the program will be significantly easier to follow since you can more easily ensure that evaluation occurs when you expect it to. Hopefully this helps. Good luck and let us know if there are further issues. Cheers, - Ben [1] http://downloads.haskell.org/~ghc/master/users-guide//profiling.html#cost-centres-and-cost-centre-stacks -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 472 bytes Desc: not available URL: From bwrogalski at gmail.com Wed May 4 16:11:34 2016 From: bwrogalski at gmail.com (Ben Rogalski) Date: Wed, 4 May 2016 12:11:34 -0400 Subject: [Haskell-beginners] Timed Profiling Message-ID: I would like to generate a time and allocation profiling report after running my program for exactly 60 seconds (on Ubuntu Linux). I compiled with the following flags: -rtsopts -auto-all -caf-all -fforce-recomp I then ran the program: The program stops after 60 seconds, but the .prof file is empty. When I run the program without using timeout, and close it manually (Alt F4, it is a graphical program), the .prof file contains the information I would expect. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bwrogalski at gmail.com Wed May 4 22:12:22 2016 From: bwrogalski at gmail.com (Ben Rogalski) Date: Wed, 4 May 2016 18:12:22 -0400 Subject: [Haskell-beginners] Double vs. Num Message-ID: I have found that using the type Double in a type signature causes my program to run much faster than if I use a type variable with a Num constraint. Is this common, and if so, why is explicitly using Double faster? -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.v2.0 at gmail.com Wed May 4 23:06:32 2016 From: tim.v2.0 at gmail.com (Tim Perry) Date: Wed, 4 May 2016 16:06:32 -0700 Subject: [Haskell-beginners] Timed Profiling In-Reply-To: References: Message-ID: I believe that timeout sends a kill signal to the process in question. I imagine that the process is killed before the profiling information is written and so you get an empty file. When you close the program with alt-F4, the program gets a chance to shut down cleanly and writes on the profiling information (.prof) On Wed, May 4, 2016 at 9:11 AM, Ben Rogalski wrote: > I would like to generate a time and allocation profiling report after > running my program for exactly 60 seconds (on Ubuntu Linux). > > I compiled with the following flags: > > -rtsopts -auto-all -caf-all -fforce-recomp > > I then ran the program: > > The program stops after 60 seconds, but the .prof file is empty. > > When I run the program without using timeout, and close it manually (Alt > F4, it is a graphical program), the .prof file contains the information I > would expect. > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.v2.0 at gmail.com Wed May 4 23:08:41 2016 From: tim.v2.0 at gmail.com (Tim Perry) Date: Wed, 4 May 2016 16:08:41 -0700 Subject: [Haskell-beginners] Double vs. Num In-Reply-To: References: Message-ID: I imagine that in this program when Double isn't specified the compiler doesn't assign a "hardware optimized" number type. Consequently it isn't using the specialized functions that are used for 64-bit floating point numbers. When the program specifies it is receiving the "Double" values, then it does use the "hardware optimized" data types. On Wed, May 4, 2016 at 3:12 PM, Ben Rogalski wrote: > I have found that using the type Double in a type signature causes my > program to run much faster than if I use a type variable with a Num > constraint. > > Is this common, and if so, why is explicitly using Double faster? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cma at bitemyapp.com Wed May 4 23:12:31 2016 From: cma at bitemyapp.com (Christopher Allen) Date: Wed, 4 May 2016 18:12:31 -0500 Subject: [Haskell-beginners] Double vs. Num In-Reply-To: References: Message-ID: <0E49E73B-2CB1-484A-9896-0EFCA671A31F@bitemyapp.com> The default if it?s a Floating type is Double. Leaving the type polymorphic breaks sharing, though, and that?s a common cause of perf issues with Num/Integral/Floating a => a computations. Best to post code when asking questions like this. > On May 4, 2016, at 6:08 PM, Tim Perry wrote: > > I imagine that in this program when Double isn't specified the compiler doesn't assign a "hardware optimized" number type. Consequently it isn't using the specialized functions that are used for 64-bit floating point numbers. When the program specifies it is receiving the "Double" values, then it does use the "hardware optimized" data types. > > On Wed, May 4, 2016 at 3:12 PM, Ben Rogalski > wrote: > I have found that using the type Double in a type signature causes my program to run much faster than if I use a type variable with a Num constraint. > > Is this common, and if so, why is explicitly using Double faster? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgf.dma at gmail.com Thu May 5 10:14:26 2016 From: sgf.dma at gmail.com (Dmitriy Matrosov) Date: Thu, 5 May 2016 13:14:26 +0300 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: > {-# LANGUAGE DataKinds, GADTs, StandaloneDeriving, Rank2Types, PolyKinds, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, ScopedTypeVariables #-} Hi. Thanks for your answer! There was quite some time passed by, but.. well, i was trying to figure out how reflection works. I've read [1] (not till the end). It's a bit too complex for me, but i thought i understand the idea how `reify` works. But still i can't understand how `reifyNat` works. Here is my code: > import Unsafe.Coerce > > data Nat = Z | S Nat > deriving (Show) > > data SNat :: Nat -> * where > SZ :: SNat 'Z > SN :: SNat n -> SNat ('S n) > deriving instance Show (SNat n) SNat is a singleton type for Nat. Then i (re-)define `reifyNat` > data Proxy s = Proxy > > class Reifies s a | s -> a where > reflect :: p s -> a > > class SNatClass (a :: Nat) where > singN :: SNat a > > instance SNatClass 'Z where > singN = SZ > instance SNatClass n => SNatClass ('S n) where > singN = SN singN > > fromSNat :: SNat n -> Nat > fromSNat SZ = Z > fromSNat (SN n) = S (fromSNat n) > {-# NOINLINE fromSNat #-} > > instance SNatClass n => Reifies n Nat where > reflect _ = fromSNat (singN :: SNat n) > > newtype MagicNat r = MagicNat (forall (n :: Nat). SNatClass n => Proxy n -> r) > > reifyNat :: forall r. Nat -> (forall (n :: Nat). SNatClass n => Proxy n -> r) -> r > reifyNat x k = unsafeCoerce (MagicNat k :: MagicNat r) x Proxy > {-# NOINLINE reifyNat #-} > > testNat :: forall (n :: Nat). SNatClass n => Proxy n -> IO () > testNat p = case (reflect p) of > Z -> print "a" > S Z -> print "b" > S (S Z) -> print "c" > _ -> print "d" > > testSNat :: forall (n :: Nat). SNatClass n => Proxy n -> IO () > testSNat p = case (singN :: SNat n) of > SZ -> print "A" > SN SZ -> print "B" > SN (SN SZ) -> print "C" > _ -> print "D" > > main = do > print (reifyNat (S (S Z)) reflect) > reifyNat (S (S Z)) testNat > reifyNat (S (S Z)) testSNat and now if i dump core: ghc-core --no-syntax --no-asm --no-cast -- -dsuppress-var-kinds -dsuppress-type-applications -dsuppress-uniques from-snat.hs i may see, that k takes two arguments: SNatClass dictionary and Proxy reifyNat = \ (@ r) (x :: Nat) (k :: forall (n :: Nat). SNatClass n => Proxy Nat n -> r) -> (k `cast` ...) x (Proxy) main7 = S Z main6 = S main7 main5 = \ (@ (n :: Nat)) ($dSNatClass :: SNatClass n) _ -> fromSNat ($dSNatClass `cast` ...) main4 = reifyNat main6 main5 but because SNatClass class has only one method, its dictionary is just a function `singN` with type `singN :: SNat a`. But if so, why we supply `x :: Nat` as dictionary in `reifyNat`? Shouldn't we supply value of type `SNat n`? No need to say, that code above works, and both `testNat` and `testSNat` find correct instance *Main> main S (S Z) "c" "C" but why? [1]: https://www.schoolofhaskell.com/user/thoughtpolice/using-reflection On Mon, Apr 11, 2016 at 4:59 PM, Marcin Mrotek wrote: > Hello, > > In your function, the type `n`, and thus also the value of the > argument, would have to be known at compile time. I'm not sure if you > could make it to work. However, you can use the reflection package > (https://hackage.haskell.org/package/reflection) where you can find a > `reifyNat` function ( > https://hackage.haskell.org/package/reflection-2.1.2/docs/Data-Reflection.html#g:1 > ) that lets you create a "temporary" type that never escapes the > callback you give to it, and so it doesn't have to be known at compile > time: > > reifyNat :: forall r. Integer -> (forall n. KnownNat n => Proxy n -> r) -> r > > The only requirement is that type `r` doesn't depend in any way on `n` > (but the computation itself can use it, it just has to return the same > type every time). > > Best regards, > Marcin Mrotek > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From marcin.jan.mrotek at gmail.com Thu May 5 11:56:37 2016 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Thu, 5 May 2016 13:56:37 +0200 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: Hello, My guess is that the Nat parameter in SNat gets erased, and both types end up with the same runtime representation. I'm not sure how reliable this is. Have you tried using a SNatClass that works more like KnownNat, that is, having a method that returns a Nat? Best regards, Marcin Mrotek From juneja.dushyant at gmail.com Thu May 5 12:43:02 2016 From: juneja.dushyant at gmail.com (Dushyant Juneja) Date: Thu, 05 May 2016 12:43:02 +0000 Subject: [Haskell-beginners] Infinite recursion in list comprehension Message-ID: Hi, I seem to be landing into infinite recursion when using higher order functions with list comprehension. Take this for an example. The following works well, and gives answers for numbers like 2000000 as well: primesBelowN :: Integer -> [Integer] primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] where f x = foldr g True xs where g t ac = (x `rem` t /= 0) && ac xs = [5, 7..(truncate (sqrt (fromInteger x)))] However, the following never returns anything for the same number, probably due to some kind of loop malfunction: primesBelowN :: Integer -> [Integer] primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] where f x = foldr g True xs where g t ac = (x `rem` t /= 0) && ac xs = [ m | m <- [5, 7, ..], m <= (truncate (sqrt (fromInteger x)))] Any ideas what might be going wrong? Thanks in advance! DJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From akaberto at gmail.com Thu May 5 13:01:15 2016 From: akaberto at gmail.com (akash g) Date: Thu, 5 May 2016 18:31:15 +0530 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: Hi Dushyant, The problem most likely is [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] This is because, the filter condition (the last part) does a very simple thing: It filters out any element that does not fulfil the criteria. You are operating on a list that is monotonically increasing. However, the filter isn't aware of this property. Hence, this list comprehension never ends because it doesn't know that once the condition fails, it will always fail. Thus, the solution would be to generate a finite set (or take a part of the infinite set using takeWhile or something like that), instead of using an infinite one. Regards, G Akash. On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja wrote: > Hi, > > I seem to be landing into infinite recursion when using higher order > functions with list comprehension. Take this for an example. The following > works well, and gives answers for numbers like 2000000 as well: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [5, 7..(truncate (sqrt > (fromInteger x)))] > > > However, the following never returns anything for the same number, > probably due to some kind of loop malfunction: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- [5, 7, ..], m <= (truncate > (sqrt (fromInteger x)))] > > Any ideas what might be going wrong? > > Thanks in advance! > > DJ > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juneja.dushyant at gmail.com Thu May 5 13:44:26 2016 From: juneja.dushyant at gmail.com (Dushyant Juneja) Date: Thu, 05 May 2016 13:44:26 +0000 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: Hi Akash, Thanks for the response. A very simple and lucid explanation. Looks interesting. So, here's the big picture now, for which I need this. I intend to implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, I intend to use the earlier function recursively, as follows: primesBelowN :: Integer -> [Integer] primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] where f x = foldr g True xs where g t ac = (x `rem` t /= 0) && ac xs = [ m | m <- primesBelowN n, m <= (truncate (sqrt (fromInteger x)))] Of course, I could do something like this: primesBelowN :: Integer -> [Integer] primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] where f x = foldr g True xs where g t ac = (x `rem` t /= 0) && ac xs = [ m | m <- primesBelowN (truncate (sqrt (fromInteger x)))] However, this calls primesBelowN function with a new argument everytime. I suppose that is not optimal (correct me if I am wrong). Point number 2: both fail. Grrh. Any ideas how I could go recursive with this function? Dushyant On Thu, May 5, 2016 at 6:31 PM akash g wrote: > Hi Dushyant, > > The problem most likely is > [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] > > This is because, the filter condition (the last part) does a very simple > thing: It filters out any element that does not fulfil the criteria. You > are operating on a list that is monotonically increasing. However, the > filter isn't aware of this property. Hence, this list comprehension never > ends because it doesn't know that once the condition fails, it will always > fail. > > Thus, the solution would be to generate a finite set (or take a part of > the infinite set using takeWhile or something like that), instead of using > an infinite one. > > Regards, > G Akash. > > On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja > wrote: > >> Hi, >> >> I seem to be landing into infinite recursion when using higher order >> functions with list comprehension. Take this for an example. The following >> works well, and gives answers for numbers like 2000000 as well: >> >> primesBelowN :: Integer -> [Integer] >> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >> 1]] >> where f x = foldr g True xs >> where g t ac = (x `rem` t /= 0) && ac >> xs = [5, 7..(truncate (sqrt >> (fromInteger x)))] >> >> >> However, the following never returns anything for the same number, >> probably due to some kind of loop malfunction: >> >> primesBelowN :: Integer -> [Integer] >> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >> 1]] >> where f x = foldr g True xs >> where g t ac = (x `rem` t /= 0) && ac >> xs = [ m | m <- [5, 7, ..], m <= (truncate >> (sqrt (fromInteger x)))] >> >> Any ideas what might be going wrong? >> >> Thanks in advance! >> >> DJ >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bwrogalski at gmail.com Thu May 5 14:10:45 2016 From: bwrogalski at gmail.com (Ben Rogalski) Date: Thu, 5 May 2016 10:10:45 -0400 Subject: [Haskell-beginners] Double vs. Num Message-ID: Tim and Christopher, here is my code. There is a lot of it, but I've tried to cut out the irrelevent parts. If I change the type of Transform3D.append from append :: (Floating a) => Transformer a -> Transform a -> Transformer a to append :: Transformer Double -> Transform Double -> Transformer Double The framerate goes from ~1400 fps to ~2200 fps. module Render where ... renderTree :: GLInfo -> Tree (Attribute Double) -> IO () renderTree (GLInfo names attribs uniforms) t = fst $ cFold2 f (return (),identity) t where f acc Hidden = Skip acc f (a,tr) (Transformation t) = Continue (a, append tr t) f (a,tr) (Clip b) = let (x1:.y1:._, x2:.y2:._) = extremes $ applyAABB tr b a' = do glUniform2f (uniforms M.! "maskMin") (realToFrac x1) (realToFrac y1) glUniform2f (uniforms M.! "maskMax") (realToFrac x2) (realToFrac y2) in Continue (a >> a', tr) f (a,tr) (Texture _ (x1:.y1:.x2:.y2:._)) = let a' = do glUniform1i (uniforms M.! "texSampler") 0 glUniform4f (uniforms M.! "uvCoords") (realToFrac x1) (realToFrac y1) (realToFrac x2) (realToFrac y2) glUniformMatrix4fv' (uniforms M.! "mvp") 1 (fromBool False) (map realToFrac $ transformerToList tr) glDrawElements gl_TRIANGLES (fromIntegral $ attribs M.! "iboLenSquare") gl_UNSIGNED_INT nullPtr in Continue (a >> a', tr) f acc _ = Continue acc ... module Transform3D where ... data Transform a = RotationZ a | Scale (Vec3 a) | Translation (Vec3 a) deriving (Eq, Read, Show) newtype Transformer a = Transformer (Vec4 (Vec4 a)) append :: (Floating a) => Transformer a -> Transform a -> Transformer a append (Transformer m) t = Transformer $ m #*# toMatrix t identity :: (Num a) => Transformer a identity = Transformer identityMatrix toMatrix :: (Floating a) => Transform a -> Vec4 (Vec4 a) toMatrix (RotationZ z) = rotationZMatrix z toMatrix (Scale (x:.y:.z:._)) = scaleMatrix x y z toMatrix (Translation (x:.y:.z:._)) = translationMatrix x y z identityMatrix :: (Num a) => Vec4 (Vec4 a) identityMatrix = (1:.0:.0:.0:.Nil):. (0:.1:.0:.0:.Nil):. (0:.0:.1:.0:.Nil):. (0:.0:.0:.1:.Nil):.Nil rotationZMatrix :: (Floating a) => a -> Vec4 (Vec4 a) rotationZMatrix a = let c = cos a s = sin a in (c:.(-s):.0:.0:.Nil):. (s:.c:.0:.0:.Nil):. (0:.0:.1:.0:.Nil):. (0:.0:.0:.1:.Nil):.Nil scaleMatrix :: (Num a) => a -> a -> a -> Vec4 (Vec4 a) scaleMatrix x y z = (x:.0:.0:.0:.Nil):. (0:.y:.0:.0:.Nil):. (0:.0:.z:.0:.Nil):. (0:.0:.0:.1:.Nil):.Nil translationMatrix :: (Num a) => a -> a -> a -> Vec4 (Vec4 a) translationMatrix x y z = (1:.0:.0:.x:.Nil):. (0:.1:.0:.y:.Nil):. (0:.0:.1:.z:.Nil):. (0:.0:.0:.1:.Nil):.Nil ... module Vector where ... infixr 5 :. --data Cons u t = (:.) t (u t) deriving (Eq, Read, Show) data Cons u t = (:.) ! t ! (u t) deriving (Eq, Read, Show) data Nil t = Nil deriving (Eq, Read, Show) ... (|*#) :: (Num t, Vector w, Vector u) => w t -> w (u t) -> u t (|*#) v m = (transpose m) #*| v (#*#) :: (Num t, Vector u, Vector v, Vector w) => u (v t) -> v (w t) -> u (w t) (#*#) x y = transpose $ fmap (x #*|) (transpose y) dot :: (Num t, Vector v) => v t -> v t -> t dot xs ys = sum ((*) <$> xs <*> ys) ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From vale.cofershabica at gmail.com Thu May 5 14:38:50 2016 From: vale.cofershabica at gmail.com (Vale Cofer-Shabica) Date: Thu, 5 May 2016 10:38:50 -0400 Subject: [Haskell-beginners] Timed Profiling In-Reply-To: References: Message-ID: timeout(1) allows you to specify the signal(7) sent with the --signal option. It may be worth experimenting with different values. One of them might terminate the program while allowing it to clean up and generate profiling information. I don't know enough about the haskell runtime to know. -vale -- vale cofer-shabica 401.267.8253 On Wed, May 4, 2016 at 7:06 PM, Tim Perry wrote: > I believe that timeout sends a kill signal to the process in question. I > imagine that the process is killed before the profiling information is > written and so you get an empty file. When you close the program with > alt-F4, the program gets a chance to shut down cleanly and writes on the > profiling information (.prof) > > > On Wed, May 4, 2016 at 9:11 AM, Ben Rogalski wrote: > >> I would like to generate a time and allocation profiling report after >> running my program for exactly 60 seconds (on Ubuntu Linux). >> >> I compiled with the following flags: >> >> -rtsopts -auto-all -caf-all -fforce-recomp >> >> I then ran the program: >> >> The program stops after 60 seconds, but the .prof file is empty. >> >> When I run the program without using timeout, and close it manually (Alt >> F4, it is a graphical program), the .prof file contains the information I >> would expect. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Thu May 5 17:57:52 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Thu, 5 May 2016 19:57:52 +0200 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: I succeeded to get it working with n = 2,000,000 at least, through this means: primesBelow :: Int -> [Int] primesBelow max = list where list = 2:3:rest rest = [ v | k <- [1..(max-1)`div`6], i <- [-1, 1] , let v = 6*k+i, checker v] ... ... the function "checker" (in the list comprehension, as conditional) is using itself in its definition the variable "list" to generate the test for each "v" of the list comprehension "rest". I dunno if this kind of recursion suits you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Thu May 5 18:10:29 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Thu, 5 May 2016 20:10:29 +0200 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: Implicitly, primesBelow shouldn't ever in fact call itself, not as it is articulated here **at the very least**, not without wasting a lot of calculus. As it is, and maybe no matter what (i'm not sure, don't have the knowledge to certify that), when primesBelow checks if a value "v" is prime or not, well no matter what it'll already have calculated and stored all primes below this value n (this, according to how primesBelow is articulated, aka filtering of Naturals bottom-top). Thus, if for each potential element "v" of the result (in my version, "list") of primesBelow, you call once again primesBelow, asking it to generate again all primes below sqrt(v), you'll do nothing more than doing again what you already did, because all those previous primes have already been generated, stored away, and especially very accessible, in the list-result in-construction of the **current** call to primesBelow, so if you don't use it but call again primesBelow to get a copy of what you already have, you'll multiply immensely the work without any gain. That's why I named the very result of primesBelow, to get a way to use "list" (the previously generated items of the future result-list) in "checker". 2016-05-05 15:44 GMT+02:00 Dushyant Juneja : > Hi Akash, > > Thanks for the response. A very simple and lucid explanation. Looks > interesting. > > So, here's the big picture now, for which I need this. I intend to > implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, > I intend to use the earlier function recursively, as follows: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN n, m > <= (truncate (sqrt (fromInteger x)))] > > Of course, I could do something like this: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN (truncate > (sqrt (fromInteger x)))] > > However, this calls primesBelowN function with a new argument everytime. I > suppose that is not optimal (correct me if I am wrong). > > Point number 2: both fail. Grrh. > > Any ideas how I could go recursive with this function? > > Dushyant > > > On Thu, May 5, 2016 at 6:31 PM akash g wrote: > >> Hi Dushyant, >> >> The problem most likely is >> [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] >> >> This is because, the filter condition (the last part) does a very simple >> thing: It filters out any element that does not fulfil the criteria. You >> are operating on a list that is monotonically increasing. However, the >> filter isn't aware of this property. Hence, this list comprehension never >> ends because it doesn't know that once the condition fails, it will always >> fail. >> >> Thus, the solution would be to generate a finite set (or take a part of >> the infinite set using takeWhile or something like that), instead of using >> an infinite one. >> >> Regards, >> G Akash. >> >> On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja < >> juneja.dushyant at gmail.com> wrote: >> >>> Hi, >>> >>> I seem to be landing into infinite recursion when using higher order >>> functions with list comprehension. Take this for an example. The following >>> works well, and gives answers for numbers like 2000000 as well: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [5, 7..(truncate (sqrt >>> (fromInteger x)))] >>> >>> >>> However, the following never returns anything for the same number, >>> probably due to some kind of loop malfunction: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [ m | m <- [5, 7, ..], m <= (truncate >>> (sqrt (fromInteger x)))] >>> >>> Any ideas what might be going wrong? >>> >>> Thanks in advance! >>> >>> DJ >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmcilroy at gmail.com Thu May 5 19:14:20 2016 From: pmcilroy at gmail.com (Peter McIlroy) Date: Thu, 5 May 2016 12:14:20 -0700 Subject: [Haskell-beginners] Beginners Digest, Vol 95, Issue 8 In-Reply-To: References: Message-ID: <572b9ba0.4334620a.74549.442c@mx.google.com> -----Original Message----- From: "beginners-request at haskell.org" Sent: ?5/?5/?2016 11:10 AM To: "beginners at haskell.org" Subject: Beginners Digest, Vol 95, Issue 8 Send Beginners mailing list submissions to beginners at haskell.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners or, via email, send a message with subject or body 'help' to beginners-request at haskell.org You can reach the person managing the list at beginners-owner at haskell.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Beginners digest..." Today's Topics: 1. Re: Timed Profiling (Vale Cofer-Shabica) 2. Re: Infinite recursion in list comprehension (Silent Leaf) 3. Re: Infinite recursion in list comprehension (Silent Leaf) ---------------------------------------------------------------------- Message: 1 Date: Thu, 5 May 2016 10:38:50 -0400 From: Vale Cofer-Shabica To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Timed Profiling Message-ID: Content-Type: text/plain; charset="utf-8" timeout(1) allows you to specify the signal(7) sent with the --signal option. It may be worth experimenting with different values. One of them might terminate the program while allowing it to clean up and generate profiling information. I don't know enough about the haskell runtime to know. -vale -- vale cofer-shabica 401.267.8253 On Wed, May 4, 2016 at 7:06 PM, Tim Perry wrote: > I believe that timeout sends a kill signal to the process in question. I > imagine that the process is killed before the profiling information is > written and so you get an empty file. When you close the program with > alt-F4, the program gets a chance to shut down cleanly and writes on the > profiling information (.prof) > > > On Wed, May 4, 2016 at 9:11 AM, Ben Rogalski wrote: > >> I would like to generate a time and allocation profiling report after >> running my program for exactly 60 seconds (on Ubuntu Linux). >> >> I compiled with the following flags: >> >> -rtsopts -auto-all -caf-all -fforce-recomp >> >> I then ran the program: >> >> The program stops after 60 seconds, but the .prof file is empty. >> >> When I run the program without using timeout, and close it manually (Alt >> F4, it is a graphical program), the .prof file contains the information I >> would expect. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Thu, 5 May 2016 19:57:52 +0200 From: Silent Leaf To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Infinite recursion in list comprehension Message-ID: Content-Type: text/plain; charset="utf-8" I succeeded to get it working with n = 2,000,000 at least, through this means: primesBelow :: Int -> [Int] primesBelow max = list where list = 2:3:rest rest = [ v | k <- [1..(max-1)`div`6], i <- [-1, 1] , let v = 6*k+i, checker v] ... ... the function "checker" (in the list comprehension, as conditional) is using itself in its definition the variable "list" to generate the test for each "v" of the list comprehension "rest". I dunno if this kind of recursion suits you. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 3 Date: Thu, 5 May 2016 20:10:29 +0200 From: Silent Leaf To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Infinite recursion in list comprehension Message-ID: Content-Type: text/plain; charset="utf-8" Implicitly, primesBelow shouldn't ever in fact call itself, not as it is articulated here **at the very least**, not without wasting a lot of calculus. As it is, and maybe no matter what (i'm not sure, don't have the knowledge to certify that), when primesBelow checks if a value "v" is prime or not, well no matter what it'll already have calculated and stored all primes below this value n (this, according to how primesBelow is articulated, aka filtering of Naturals bottom-top). Thus, if for each potential element "v" of the result (in my version, "list") of primesBelow, you call once again primesBelow, asking it to generate again all primes below sqrt(v), you'll do nothing more than doing again what you already did, because all those previous primes have already been generated, stored away, and especially very accessible, in the list-result in-construction of the **current** call to primesBelow, so if you don't use it but call again primesBelow to get a copy of what you already have, you'll multiply immensely the work without any gain. That's why I named the very result of primesBelow, to get a way to use "list" (the previously generated items of the future result-list) in "checker". 2016-05-05 15:44 GMT+02:00 Dushyant Juneja : > Hi Akash, > > Thanks for the response. A very simple and lucid explanation. Looks > interesting. > > So, here's the big picture now, for which I need this. I intend to > implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, > I intend to use the earlier function recursively, as follows: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN n, m > <= (truncate (sqrt (fromInteger x)))] > > Of course, I could do something like this: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN (truncate > (sqrt (fromInteger x)))] > > However, this calls primesBelowN function with a new argument everytime. I > suppose that is not optimal (correct me if I am wrong). > > Point number 2: both fail. Grrh. > > Any ideas how I could go recursive with this function? > > Dushyant > > > On Thu, May 5, 2016 at 6:31 PM akash g wrote: > >> Hi Dushyant, >> >> The problem most likely is >> [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] >> >> This is because, the filter condition (the last part) does a very simple >> thing: It filters out any element that does not fulfil the criteria. You >> are operating on a list that is monotonically increasing. However, the >> filter isn't aware of this property. Hence, this list comprehension never >> ends because it doesn't know that once the condition fails, it will always >> fail. >> >> Thus, the solution would be to generate a finite set (or take a part of >> the infinite set using takeWhile or something like that), instead of using >> an infinite one. >> >> Regards, >> G Akash. >> >> On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja < >> juneja.dushyant at gmail.com> wrote: >> >>> Hi, >>> >>> I seem to be landing into infinite recursion when using higher order >>> functions with list comprehension. Take this for an example. The following >>> works well, and gives answers for numbers like 2000000 as well: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [5, 7..(truncate (sqrt >>> (fromInteger x)))] >>> >>> >>> However, the following never returns anything for the same number, >>> probably due to some kind of loop malfunction: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [ m | m <- [5, 7, ..], m <= (truncate >>> (sqrt (fromInteger x)))] >>> >>> Any ideas what might be going wrong? >>> >>> Thanks in advance! >>> >>> DJ >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Subject: Digest Footer _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners ------------------------------ End of Beginners Digest, Vol 95, Issue 8 **************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmcilroy at gmail.com Thu May 5 19:18:41 2016 From: pmcilroy at gmail.com (Peter McIlroy) Date: Thu, 5 May 2016 12:18:41 -0700 Subject: [Haskell-beginners] Sieve of Aritosthenes In-Reply-To: References: Message-ID: <572b9ca7.4b99420a.de761.456a@mx.google.com> Apologies for the empty post. You might turn your attention to the following web page, which approaches the problem using recursive co-routines. Amidst a discussion of UNIX pipes, both in history and as a primitive co-routine implementation, there is a two-line Haskell program. http://www.cs.dartmouth.edu/~doug/sieve/ -----Original Message----- From: "beginners-request at haskell.org" Sent: ?5/?5/?2016 11:10 AM To: "beginners at haskell.org" Subject: Beginners Digest, Vol 95, Issue 8 Send Beginners mailing list submissions to beginners at haskell.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners or, via email, send a message with subject or body 'help' to beginners-request at haskell.org You can reach the person managing the list at beginners-owner at haskell.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Beginners digest..." Today's Topics: 1. Re: Timed Profiling (Vale Cofer-Shabica) 2. Re: Infinite recursion in list comprehension (Silent Leaf) 3. Re: Infinite recursion in list comprehension (Silent Leaf) ---------------------------------------------------------------------- Message: 1 Date: Thu, 5 May 2016 10:38:50 -0400 From: Vale Cofer-Shabica To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Timed Profiling Message-ID: Content-Type: text/plain; charset="utf-8" timeout(1) allows you to specify the signal(7) sent with the --signal option. It may be worth experimenting with different values. One of them might terminate the program while allowing it to clean up and generate profiling information. I don't know enough about the haskell runtime to know. -vale -- vale cofer-shabica 401.267.8253 On Wed, May 4, 2016 at 7:06 PM, Tim Perry wrote: > I believe that timeout sends a kill signal to the process in question. I > imagine that the process is killed before the profiling information is > written and so you get an empty file. When you close the program with > alt-F4, the program gets a chance to shut down cleanly and writes on the > profiling information (.prof) > > > On Wed, May 4, 2016 at 9:11 AM, Ben Rogalski wrote: > >> I would like to generate a time and allocation profiling report after >> running my program for exactly 60 seconds (on Ubuntu Linux). >> >> I compiled with the following flags: >> >> -rtsopts -auto-all -caf-all -fforce-recomp >> >> I then ran the program: >> >> The program stops after 60 seconds, but the .prof file is empty. >> >> When I run the program without using timeout, and close it manually (Alt >> F4, it is a graphical program), the .prof file contains the information I >> would expect. >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Thu, 5 May 2016 19:57:52 +0200 From: Silent Leaf To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Infinite recursion in list comprehension Message-ID: Content-Type: text/plain; charset="utf-8" I succeeded to get it working with n = 2,000,000 at least, through this means: primesBelow :: Int -> [Int] primesBelow max = list where list = 2:3:rest rest = [ v | k <- [1..(max-1)`div`6], i <- [-1, 1] , let v = 6*k+i, checker v] ... ... the function "checker" (in the list comprehension, as conditional) is using itself in its definition the variable "list" to generate the test for each "v" of the list comprehension "rest". I dunno if this kind of recursion suits you. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 3 Date: Thu, 5 May 2016 20:10:29 +0200 From: Silent Leaf To: The Haskell-Beginners Mailing List - Discussion of primarily beginner-level topics related to Haskell Subject: Re: [Haskell-beginners] Infinite recursion in list comprehension Message-ID: Content-Type: text/plain; charset="utf-8" Implicitly, primesBelow shouldn't ever in fact call itself, not as it is articulated here **at the very least**, not without wasting a lot of calculus. As it is, and maybe no matter what (i'm not sure, don't have the knowledge to certify that), when primesBelow checks if a value "v" is prime or not, well no matter what it'll already have calculated and stored all primes below this value n (this, according to how primesBelow is articulated, aka filtering of Naturals bottom-top). Thus, if for each potential element "v" of the result (in my version, "list") of primesBelow, you call once again primesBelow, asking it to generate again all primes below sqrt(v), you'll do nothing more than doing again what you already did, because all those previous primes have already been generated, stored away, and especially very accessible, in the list-result in-construction of the **current** call to primesBelow, so if you don't use it but call again primesBelow to get a copy of what you already have, you'll multiply immensely the work without any gain. That's why I named the very result of primesBelow, to get a way to use "list" (the previously generated items of the future result-list) in "checker". 2016-05-05 15:44 GMT+02:00 Dushyant Juneja : > Hi Akash, > > Thanks for the response. A very simple and lucid explanation. Looks > interesting. > > So, here's the big picture now, for which I need this. I intend to > implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, > I intend to use the earlier function recursively, as follows: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN n, m > <= (truncate (sqrt (fromInteger x)))] > > Of course, I could do something like this: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = [ m | m <- primesBelowN (truncate > (sqrt (fromInteger x)))] > > However, this calls primesBelowN function with a new argument everytime. I > suppose that is not optimal (correct me if I am wrong). > > Point number 2: both fail. Grrh. > > Any ideas how I could go recursive with this function? > > Dushyant > > > On Thu, May 5, 2016 at 6:31 PM akash g wrote: > >> Hi Dushyant, >> >> The problem most likely is >> [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] >> >> This is because, the filter condition (the last part) does a very simple >> thing: It filters out any element that does not fulfil the criteria. You >> are operating on a list that is monotonically increasing. However, the >> filter isn't aware of this property. Hence, this list comprehension never >> ends because it doesn't know that once the condition fails, it will always >> fail. >> >> Thus, the solution would be to generate a finite set (or take a part of >> the infinite set using takeWhile or something like that), instead of using >> an infinite one. >> >> Regards, >> G Akash. >> >> On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja < >> juneja.dushyant at gmail.com> wrote: >> >>> Hi, >>> >>> I seem to be landing into infinite recursion when using higher order >>> functions with list comprehension. Take this for an example. The following >>> works well, and gives answers for numbers like 2000000 as well: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [5, 7..(truncate (sqrt >>> (fromInteger x)))] >>> >>> >>> However, the following never returns anything for the same number, >>> probably due to some kind of loop malfunction: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [ m | m <- [5, 7, ..], m <= (truncate >>> (sqrt (fromInteger x)))] >>> >>> Any ideas what might be going wrong? >>> >>> Thanks in advance! >>> >>> DJ >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Subject: Digest Footer _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners ------------------------------ End of Beginners Digest, Vol 95, Issue 8 **************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmcilroy at gmail.com Thu May 5 19:57:24 2016 From: pmcilroy at gmail.com (Peter McIlroy) Date: Thu, 5 May 2016 12:57:24 -0700 Subject: [Haskell-beginners] Apology Message-ID: <572ba5b1.4f19620a.348a9.4997@mx.google.com> Apologies for the two bad messages. I won't attempt responding by phone to this list anymore. -------------- next part -------------- An HTML attachment was scrubbed... URL: From juneja.dushyant at gmail.com Fri May 6 07:48:24 2016 From: juneja.dushyant at gmail.com (Dushyant Juneja) Date: Fri, 06 May 2016 07:48:24 +0000 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: Silent Leaf, Akash, Thanks for your inputs. I think my issue got sorted out. As Akash pointed out, the issue lies with the truncation condition never being met for some cases. I got this finally working using 'takeWhile'. The recursion is as elegant now: primesBelowN :: Integer -> [Integer] primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] where f x = foldr g True xs where g t ac = (x `rem` t /= 0) && ac xs = takeWhile (<= squareRoot x) $ primesBelowN n Since squareRoot x will never be more than x, the recursion has no opportunity to overflow to infinity. Thanks for your inputs! Having said all of this, I now realize that this is not really the Sieve of Eratosthenes, but an optimized trial division method. Thanks to this, now I know something more about list comprehension and its pitfalls. And some things about optimization in haskell. Thanks again for your time and effort. Dushyant On Thu, May 5, 2016 at 11:41 PM Silent Leaf wrote: > Implicitly, primesBelow shouldn't ever in fact call itself, not as it is > articulated here **at the very least**, not without wasting a lot of > calculus. > > As it is, and maybe no matter what (i'm not sure, don't have the knowledge > to certify that), when primesBelow checks if a value "v" is prime or not, > well no matter what it'll already have calculated and stored all primes > below this value n (this, according to how primesBelow is articulated, aka > filtering of Naturals bottom-top). > > Thus, if for each potential element "v" of the result (in my version, > "list") of primesBelow, you call once again primesBelow, asking it to > generate again all primes below sqrt(v), you'll do nothing more than doing > again what you already did, because all those previous primes have already > been generated, stored away, and especially very accessible, in the > list-result in-construction of the **current** call to primesBelow, so if > you don't use it but call again primesBelow to get a copy of what you > already have, you'll multiply immensely the work without any gain. > That's why I named the very result of primesBelow, to get a way to use > "list" (the previously generated items of the future result-list) in > "checker". > > 2016-05-05 15:44 GMT+02:00 Dushyant Juneja : > >> Hi Akash, >> >> Thanks for the response. A very simple and lucid explanation. Looks >> interesting. >> >> So, here's the big picture now, for which I need this. I intend to >> implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, >> I intend to use the earlier function recursively, as follows: >> >> primesBelowN :: Integer -> [Integer] >> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >> 1]] >> where f x = foldr g True xs >> where g t ac = (x `rem` t /= 0) && ac >> xs = [ m | m <- primesBelowN n, m >> <= (truncate (sqrt (fromInteger x)))] >> >> Of course, I could do something like this: >> >> primesBelowN :: Integer -> [Integer] >> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >> 1]] >> where f x = foldr g True xs >> where g t ac = (x `rem` t /= 0) && ac >> xs = [ m | m <- primesBelowN (truncate >> (sqrt (fromInteger x)))] >> >> However, this calls primesBelowN function with a new argument everytime. >> I suppose that is not optimal (correct me if I am wrong). >> >> Point number 2: both fail. Grrh. >> >> Any ideas how I could go recursive with this function? >> >> Dushyant >> >> >> On Thu, May 5, 2016 at 6:31 PM akash g wrote: >> >>> Hi Dushyant, >>> >>> The problem most likely is >>> [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] >>> >>> This is because, the filter condition (the last part) does a very >>> simple thing: It filters out any element that does not fulfil the >>> criteria. You are operating on a list that is monotonically increasing. >>> However, the filter isn't aware of this property. Hence, this list >>> comprehension never ends because it doesn't know that once the condition >>> fails, it will always fail. >>> >>> Thus, the solution would be to generate a finite set (or take a part of >>> the infinite set using takeWhile or something like that), instead of using >>> an infinite one. >>> >>> Regards, >>> G Akash. >>> >>> On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja < >>> juneja.dushyant at gmail.com> wrote: >>> >>>> Hi, >>>> >>>> I seem to be landing into infinite recursion when using higher order >>>> functions with list comprehension. Take this for an example. The following >>>> works well, and gives answers for numbers like 2000000 as well: >>>> >>>> primesBelowN :: Integer -> [Integer] >>>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>>> 1]] >>>> where f x = foldr g True xs >>>> where g t ac = (x `rem` t /= 0) && ac >>>> xs = [5, 7..(truncate (sqrt >>>> (fromInteger x)))] >>>> >>>> >>>> However, the following never returns anything for the same number, >>>> probably due to some kind of loop malfunction: >>>> >>>> primesBelowN :: Integer -> [Integer] >>>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>>> 1]] >>>> where f x = foldr g True xs >>>> where g t ac = (x `rem` t /= 0) && ac >>>> xs = [ m | m <- [5, 7, ..], m <= (truncate >>>> (sqrt (fromInteger x)))] >>>> >>>> Any ideas what might be going wrong? >>>> >>>> Thanks in advance! >>>> >>>> DJ >>>> >>>> _______________________________________________ >>>> Beginners mailing list >>>> Beginners at haskell.org >>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>>> >>>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgf.dma at gmail.com Fri May 6 10:42:18 2016 From: sgf.dma at gmail.com (Dmitriy Matrosov) Date: Fri, 6 May 2016 13:42:18 +0300 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: > {-# LANGUAGE DataKinds, GADTs, StandaloneDeriving, Rank2Types, PolyKinds, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, ScopedTypeVariables #-} > > import Unsafe.Coerce > Have you tried using a SNatClass that works more like > KnownNat, that is, having a method that returns a Nat? I don't sure what you mean, but i've checked now the differences between my code and reflection package, and there are some substantial ones. I define Nat as data Nat = Z | S Nat but they define only kind > data Nat Hm, well.. then we have similar definition of SNat class: class SNatClass (a :: Nat) where singN :: SNat a > class KnownNat (n :: Nat) where > natSing :: SNat n but very different definition of SNat itself: data SNat :: Nat -> * where SZ :: SNat 'Z SN :: SNat n -> SNat ('S n) against > newtype SNat (n :: Nat) = SNat Integer > deriving instance Show (SNat n) and from this follows another main difference: i've defined instances of SNatClass: instance SNatClass 'Z where singN = SZ instance SNatClass n => SNatClass ('S n) where singN = SN singN but they're not (and, if i'm correct, they can't, because there is no types with kind Nat (remember, they've defined only kind)). And then the identical code: > data Proxy s = Proxy > > class Reifies s a | s -> a where > reflect :: p s -> a > > natVal :: forall n proxy. KnownNat n => proxy n -> Integer > natVal _ = case natSing :: SNat n of > SNat x -> x > > instance KnownNat n => Reifies n Integer where > reflect = natVal > > newtype MagicNat r = MagicNat (forall (n :: Nat). KnownNat n => Proxy n -> r) > > reifyNat :: forall r. Integer -> (forall (n :: Nat). KnownNat n => Proxy n -> r) -> r > reifyNat x k = unsafeCoerce (MagicNat k :: MagicNat r) x Proxy > {-# NOINLINE reifyNat #-} > > main = do > print $ reifyNat 4 reflect > print $ reifyNat 4 natVal > reifyNat 4 (print . asNatProxyTypeOf natSing) > --reifyNat 4 (print . asWrongNatProxyTypeOf natSing) > > -- Note the type: type argument in `SNat n` is the same as for Proxy. Thus, i > -- will found exactly KnownNat instance, which i have defined in > -- `reifyNat`. > asNatProxyTypeOf :: KnownNat n => SNat n -> Proxy n -> SNat n > asNatProxyTypeOf = const > > -- On the other hand, if type will be `KnownNat n => SNat r -> Proxy n -> > -- SNat r`, then i won't be able to find correct instance of `KnownNat r` and > -- thus can't e.g. print `SNat r` value. > asWrongNatProxyTypeOf :: KnownNat n => SNat r -> Proxy n -> SNat r > asWrongNatProxyTypeOf = const So, you're right: `reifyNat` defines dictionary for `KnownNat n` (and this is the only instance we have) as Integer. But though dictionary is a function `natSing :: SNat n`, now SNat is newtype and its runtime representation should indeed be equivalent to Integer and all is fine. Well, ok, i think i understand how correct `reifyNat` works. Thanks! But i still don't understand why mine works too, though is probably wrong. On Thu, May 5, 2016 at 2:56 PM, Marcin Mrotek wrote: > Hello, > > My guess is that the Nat parameter in SNat gets erased, and both types > end up with the same runtime representation. I'm not sure how reliable > this is. Have you tried using a SNatClass that works more like > KnownNat, that is, having a method that returns a Nat? > > Best regards, > Marcin Mrotek > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From marcin.jan.mrotek at gmail.com Fri May 6 11:24:55 2016 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Fri, 6 May 2016 13:24:55 +0200 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: > I don't sure what you mean, but i've checked now the differences between my > code and reflection package, and there are some substantial ones. Sorry, I thought that natVal is a part of KnownNat, and I didn't bother to check. > but they're not (and, if i'm correct, they can't, because there is no types > with kind Nat (remember, they've defined only kind)). Nat is somewhat magic, as it's built into GHC. Type literals like 0,1,2,3... are all legal types of this kind. It is possible to write type class instances for them, but they're uninhabited, and thus can only be used as parameters for other types. I guess KnownNat is just magic too, but I think in principle it could be defined by induction, though the last time I've checked GHC had problems with realizing that '0' and 'n + 1' are not overlapping. > So, you're right: `reifyNat` defines dictionary for `KnownNat n` (and > this is the only instance we have) as Integer. But though dictionary is a > function `natSing :: SNat n`, now SNat is newtype and its runtime > representation should indeed be equivalent to Integer and all is fine. > > Well, ok, i think i understand how correct `reifyNat` works. Thanks! > > But i still don't understand why mine works too, though is probably wrong. I think that, while "newtype SNat (n :: Nat) = SNat Integer" is reliably coercible to Integer, your SNat happens to be coercible to your Nat too, but again, I have no idea if this is the expected behavior. It's playing with unsafeCoerce and GHC internals after all, so weird things can happen. You could define SNat as something "newtype SNat (n :: Nat) = SNat Nat" to be on the safer side, and then define SNatClass and natVal as something like: class SNatClass (n :: Nat) where singN :: SNat n instance SNatClass Z where singN = SNat Z instance SNatClass n => SNatClass (S n) where singN = SNat (S n) where SNat n = (singN :: SNat n) natVal :: forall n proxy. SNatClass n => proxy n -> Nat natVal _ = case (singN :: SNat n) of SNat n -> n Best regards, Marcin Mrotek From silent.leaf0 at gmail.com Fri May 6 15:35:45 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 6 May 2016 17:35:45 +0200 Subject: [Haskell-beginners] Infinite recursion in list comprehension In-Reply-To: References: Message-ID: I don't think you have understood me. your recursive call will do a huge amount of work several times uselessly. for each x, *after* having checked [4..x-1] of your list comprehension for primeness, every value of [4.. square(x)] would again be calculated by your recursive call, instead of using the same result of the current call (what i called "list" in my version of it), then for every of those values, the recursive call would calculate *again* the exact same values, say, for square(x), [4.. square(square(x))], etc until it reaches the beginning of the list. in other terms, everytime you call primeBelow inside itself, it'll create a new scope, with a new identical result list (2:3: ...), and will try to calculate **again** the first items until it reaches the square root of x, a work which at the time this recursive call is made, is necessarily **already** done! think about it: this x is the one in the list comprehension that is currently being processed to know if it is prime or not. it means every n < x has already been processed inside the result-in-construction ("list" in my example) of your **current** call to (primeBelow n). this expression: primeBelow n = list where list = ... implies that (primeBelow n) precisely is identical to "list" (lazily speaking), so if you use the value "list" instead of a new call, you'll get necessarily the same values under square(x), except they won't have to be calculated again the only other scenario of course is endless recursive call, but you mentioned it yourself, which makes me think implicitly you know what i'm trying to explain, since you said yourself: "Since squareRoot x will never be more than x, the recursion has no opportunity to overflow to infinity." you knkow that in the recursive call to, basically, (primeBelow square(x)), x itself would never be reached **because** (square x) is being checked **before** x is ever reached, which implies that, in the **current** main call to primeBelow, since we do are checking (x) (and are in need of the first primes under square x), then all primes under square(x) will **already** have been calculated *before**, are already known, in this very call, in a value you have to name, and which i named "list". 2016-05-06 9:48 GMT+02:00 Dushyant Juneja : > Silent Leaf, Akash, > > Thanks for your inputs. I think my issue got sorted out. As Akash pointed > out, the issue lies with the truncation condition never being met for some > cases. I got this finally working using 'takeWhile'. The recursion is as > elegant now: > > primesBelowN :: Integer -> [Integer] > primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, 1]] > where f x = foldr g True xs > where g t ac = (x `rem` t /= 0) && ac > xs = takeWhile (<= squareRoot x) $ > primesBelowN n > > Since squareRoot x will never be more than x, the recursion has no > opportunity to overflow to infinity. > > Thanks for your inputs! > > Having said all of this, I now realize that this is not really the Sieve > of Eratosthenes, but an optimized trial division method. Thanks to this, > now I know something more about list comprehension and its pitfalls. And > some things about optimization in haskell. > > Thanks again for your time and effort. > > Dushyant > > On Thu, May 5, 2016 at 11:41 PM Silent Leaf > wrote: > >> Implicitly, primesBelow shouldn't ever in fact call itself, not as it is >> articulated here **at the very least**, not without wasting a lot of >> calculus. >> >> As it is, and maybe no matter what (i'm not sure, don't have the >> knowledge to certify that), when primesBelow checks if a value "v" is prime >> or not, well no matter what it'll already have calculated and stored all >> primes below this value n (this, according to how primesBelow is >> articulated, aka filtering of Naturals bottom-top). >> >> Thus, if for each potential element "v" of the result (in my version, >> "list") of primesBelow, you call once again primesBelow, asking it to >> generate again all primes below sqrt(v), you'll do nothing more than doing >> again what you already did, because all those previous primes have already >> been generated, stored away, and especially very accessible, in the >> list-result in-construction of the **current** call to primesBelow, so if >> you don't use it but call again primesBelow to get a copy of what you >> already have, you'll multiply immensely the work without any gain. >> That's why I named the very result of primesBelow, to get a way to use >> "list" (the previously generated items of the future result-list) in >> "checker". >> >> 2016-05-05 15:44 GMT+02:00 Dushyant Juneja : >> >>> Hi Akash, >>> >>> Thanks for the response. A very simple and lucid explanation. Looks >>> interesting. >>> >>> So, here's the big picture now, for which I need this. I intend to >>> implement a lookalike Sieve of Eratosthenes algorithm in haskell. For this, >>> I intend to use the earlier function recursively, as follows: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [ m | m <- primesBelowN n, m >>> <= (truncate (sqrt (fromInteger x)))] >>> >>> Of course, I could do something like this: >>> >>> primesBelowN :: Integer -> [Integer] >>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- [-1, >>> 1]] >>> where f x = foldr g True xs >>> where g t ac = (x `rem` t /= 0) && ac >>> xs = [ m | m <- primesBelowN (truncate >>> (sqrt (fromInteger x)))] >>> >>> However, this calls primesBelowN function with a new argument everytime. >>> I suppose that is not optimal (correct me if I am wrong). >>> >>> Point number 2: both fail. Grrh. >>> >>> Any ideas how I could go recursive with this function? >>> >>> Dushyant >>> >>> >>> On Thu, May 5, 2016 at 6:31 PM akash g wrote: >>> >>>> Hi Dushyant, >>>> >>>> The problem most likely is >>>> [m | m <- [5,7..], m <= (truncate (sqrt (fromInteger x)))] >>>> >>>> This is because, the filter condition (the last part) does a very >>>> simple thing: It filters out any element that does not fulfil the >>>> criteria. You are operating on a list that is monotonically increasing. >>>> However, the filter isn't aware of this property. Hence, this list >>>> comprehension never ends because it doesn't know that once the condition >>>> fails, it will always fail. >>>> >>>> Thus, the solution would be to generate a finite set (or take a part of >>>> the infinite set using takeWhile or something like that), instead of using >>>> an infinite one. >>>> >>>> Regards, >>>> G Akash. >>>> >>>> On Thu, May 5, 2016 at 6:13 PM, Dushyant Juneja < >>>> juneja.dushyant at gmail.com> wrote: >>>> >>>>> Hi, >>>>> >>>>> I seem to be landing into infinite recursion when using higher order >>>>> functions with list comprehension. Take this for an example. The following >>>>> works well, and gives answers for numbers like 2000000 as well: >>>>> >>>>> primesBelowN :: Integer -> [Integer] >>>>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- >>>>> [-1, 1]] >>>>> where f x = foldr g True xs >>>>> where g t ac = (x `rem` t /= 0) && ac >>>>> xs = [5, 7..(truncate (sqrt >>>>> (fromInteger x)))] >>>>> >>>>> >>>>> However, the following never returns anything for the same number, >>>>> probably due to some kind of loop malfunction: >>>>> >>>>> primesBelowN :: Integer -> [Integer] >>>>> primesBelowN n = 2:3:filter f [6*k+i | k <- [1..(n-1)`div`6], i <- >>>>> [-1, 1]] >>>>> where f x = foldr g True xs >>>>> where g t ac = (x `rem` t /= 0) && ac >>>>> xs = [ m | m <- [5, 7, ..], m >>>>> <= (truncate (sqrt (fromInteger x)))] >>>>> >>>>> Any ideas what might be going wrong? >>>>> >>>>> Thanks in advance! >>>>> >>>>> DJ >>>>> >>>>> _______________________________________________ >>>>> Beginners mailing list >>>>> Beginners at haskell.org >>>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>>>> >>>>> >>>> _______________________________________________ >>>> Beginners mailing list >>>> Beginners at haskell.org >>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>>> >>> >>> _______________________________________________ >>> Beginners mailing list >>> Beginners at haskell.org >>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >>> >>> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From miguel.a.santos.l at gmail.com Sun May 8 14:05:57 2016 From: miguel.a.santos.l at gmail.com (Miguel A. Santos) Date: Sun, 8 May 2016 10:05:57 -0400 Subject: [Haskell-beginners] Automatic differentiation (AD) with respect to list of matrices in Haskell Message-ID: I am trying to understand how can I use Numeric.AD (automatic differentiation) in Haskell. I defined a simple matrix type and a scalar function taking an array and two matrices as arguments. I want to use AD to get the gradient of the scoring function with respect to both matrices, but I'm running into compilation problems. Here is the code: ------------------------------- {-# LANGUAGE DeriveTraversable, DeriveFunctor, DeriveFoldable #-}import Numeric.AD.Mode.Reverse as Rimport Data.Traversable as Timport Data.Foldable as F --- Non-linear function on "vectors" logistic x = 1.0 / (1.0 + exp(-x) ) phi v = map logistic v phi' (x:xs) = x : (phi xs) --- dot product dot u v = foldr (+) 0 $ zipWith (*) u v --- simple matrix typedata Matrix a = M [[a]] deriving (Eq,Show,Functor,F.Foldable,T.Traversable) --- action of a matrix on a vector mv _ [] = [] mv (M []) _ = [] mv ( M m ) v = ( dot (head m) v ) : (mv (M (tail m)) v ) --- two matrices mbW1 = M $ [[1,0,0],[-1,5,1],[1,2,-3]] mbW2 = M $ [[0,0,0],[1,3,-1],[-2,4,6]] --- two different scoring functions sc1 v m = foldr (+) 0 $ (phi' . (mv m) ) v sc2 :: Floating a => [a] -> [Matrix a] -> a sc2 v [m1, m2] = foldr (+) 0 $ (phi' . (mv m2) . phi' . (mv m1) ) v strToInt = read :: String -> Double strLToIntL = map strToInt--- testing main = do putStrLn $ "mbW1:" ++ (show mbW1) putStrLn $ "mbW2:" ++ (show mbW2) rawInput <- readFile "/dev/stdin" let xin= strLToIntL $ lines rawInput putStrLn "sc xin mbW1" print $ sc1 xin mbW1 --- ok. = putStrLn "grad (sc1 xin) mbW1" print $ grad ( sc1 xin) mbW1 -- yields an error: expects xin [Reverse s Double] instead of [Double] putStrLn "grad (sc1 [3,5,7]) mbW1" print $ grad ( sc1 [3,5,7]) mbW1 --- ok. = putStrLn "sc2 xin [mbW1,mbW2]" print $ sc2 xin [mbW1, mbW2] putStrLn "grad (sc2 [3,5,7) [mbW1,mbW2]" print $ grad ( sc2 [3,5,7]) [mbW1, mbW2] --- Error: see text -------------------------------- The last line (grad on sc2) gives the following error: --------------------------------- Couldn't match type ?Reverse s (Matrix Double)? with ?Matrix (Reverse s (Matrix Double))? Expected type: [Reverse s (Matrix Double)] -> Reverse s (Matrix Double) Actual type: [Matrix (Reverse s (Matrix Double))] -> Reverse s (Matrix Double) In the first argument of ?grad?, namely ?(sc2 [3, 5, 7])? In the second argument of ?($)?, namely ?grad (sc2 [3, 5, 7]) [mbW1, mbW2]? --------------------------------- I don't understand where the "Matrix of Matrix" in the actual type seen comes from. I'm feeding the grad with a curried version of sc2, making it a function on a list of Matrix. Commenting out the two offending lines runs without problem, i.e., the first gradient works and is correctly calculated (I'm feeding [1,2,3] as input to the program): ------------------- mbW1:M [[1.0,0.0,0.0],[-1.0,5.0,1.0],[1.0,2.0,-3.0]] mbW2:M [[0.0,0.0,0.0],[1.0,3.0,-1.0],[-2.0,4.0,6.0]] sc1 xin mbW11232.0179800657874893 grad (sc1 [3,5,7]) mbW1 M [[3.0,5.0,7.0],[7.630996942126885e-13,1.2718328236878141e-12,1.7805659531629398e-12],[1.0057130122694228e-3,1.6761883537823711e-3,2.3466636952953197e-3]] sc2 xin [mbW1,mbW2]1.8733609463863194 ------------------- Both errors are an issue. I want to take the gradient of any such sc2 scoring function, depending on an array of matrices, evaluated at any given "point" xin. Clearly, I'm not yet understanding the AD library well enough. Any help would be appreciated. -- Public key ID: E8FE60D7 Public key server: see, e.g., hkp://keys.gnupg.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From vilpesh at gmail.com Sun May 8 15:07:20 2016 From: vilpesh at gmail.com (Vilpesh Mistry) Date: Sun, 8 May 2016 20:37:20 +0530 Subject: [Haskell-beginners] Simple function gives UTF-8 decoding error. Message-ID: Haskell version installed on my computer with OS Windows 7, 64 bit. GHCi, version 7.8.3 My haskell script is in a file named baby.hs with following functions, doubleMe x = x + x doubleUs x y = x*2 + y*2 removeNonUpperCase :: [Char] -> [Char] removeNonUpperCase st = [c | c <- st, c `?lem` ['A'..'Z']] I get following error:- g>:l baby [1 of 1] Compiling Main ( baby.hs, interpreted ) baby.hs:6:42: lexical error (UTF-8 decoding error) Failed, modules loaded: none. I am not able to advance any further, please suggest. -- thanks Vilpesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From imantc at gmail.com Sun May 8 15:34:56 2016 From: imantc at gmail.com (Imants Cekusins) Date: Sun, 8 May 2016 17:34:56 +0200 Subject: [Haskell-beginners] Simple function gives UTF-8 decoding error. In-Reply-To: References: Message-ID: ? in ?lem? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From vilpesh at gmail.com Sun May 8 18:04:11 2016 From: vilpesh at gmail.com (Vilpesh Mistry) Date: Sun, 8 May 2016 23:34:11 +0530 Subject: [Haskell-beginners] Simple function gives UTF-8 decoding error. In-Reply-To: References: Message-ID: Yes, ? in ?lem was the problem, thanks for pointing that out. Vilpesh On Sun, May 8, 2016 at 9:04 PM, Imants Cekusins wrote: > ? in ?lem? > ? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- thanks Vilpesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From anvikakumar93 at gmail.com Mon May 9 04:11:01 2016 From: anvikakumar93 at gmail.com (Anvika Kumar) Date: Mon, 9 May 2016 13:11:01 +0900 Subject: [Haskell-beginners] searching for an element from a list of tuples Message-ID: I have a tuple with three values and i want to remove the tuple which contains a particular name. So d = (name, month, date) i take a user input of name and then search the list which has tuples of the above declared type. Which ever tuple has the name it should be deleted from the list. d is the tuple. db should be a list of tuples. remove :: (Eq) => IO String -> d print "Enter the name to be removed? a <- getLine remove x [] = [] print ?Record not found? remove x db = if x == Please let me know! Thanks a lot -------------- next part -------------- An HTML attachment was scrubbed... URL: From sumit.sahrawat.apm13 at iitbhu.ac.in Mon May 9 09:25:18 2016 From: sumit.sahrawat.apm13 at iitbhu.ac.in (Sumit Sahrawat, Maths & Computing, IIT (BHU)) Date: Mon, 9 May 2016 14:55:18 +0530 Subject: [Haskell-beginners] searching for an element from a list of tuples In-Reply-To: References: Message-ID: Try pattern matching on the list head and tail as in (x:xs). Take a look at the source code for filter [1], which can be put to use here. [1]: http://hackage.haskell.org/package/base-4.8.2.0/docs/src/GHC.List.html#filter Regards, Sumit On 09-May-2016 9:41 am, "Anvika Kumar" wrote: > I have a tuple with three values and i want to remove the tuple which > contains a particular name. > > So d = (name, month, date) > i take a user input of name and then search the list which has tuples of > the above declared type. Which ever tuple has the name it should be deleted > from the list. > > d is the tuple. > db should be a list of tuples. > > > remove :: (Eq) => IO String -> d > print "Enter the name to be removed? > a <- getLine > remove x [] = [] > print ?Record not found? > remove x db = > if x == > > > > Please let me know! > > Thanks a lot > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anvikakumar93 at gmail.com Mon May 9 12:02:49 2016 From: anvikakumar93 at gmail.com (Anvika Kumar) Date: Mon, 9 May 2016 21:02:49 +0900 Subject: [Haskell-beginners] searching for an element from a list of tuples In-Reply-To: References: Message-ID: Let me review and get back. Thank you. Anvika Graduate Student STONY BROOK UNIVERSITY On Mon, May 9, 2016 at 6:25 PM, Sumit Sahrawat, Maths & Computing, IIT (BHU) wrote: > Try pattern matching on the list head and tail as in (x:xs). Take a look > at the source code for filter [1], which can be put to use here. > > [1]: > http://hackage.haskell.org/package/base-4.8.2.0/docs/src/GHC.List.html#filter > > Regards, > Sumit > On 09-May-2016 9:41 am, "Anvika Kumar" wrote: > >> I have a tuple with three values and i want to remove the tuple which >> contains a particular name. >> >> So d = (name, month, date) >> i take a user input of name and then search the list which has tuples of >> the above declared type. Which ever tuple has the name it should be deleted >> from the list. >> >> d is the tuple. >> db should be a list of tuples. >> >> >> remove :: (Eq) => IO String -> d >> print "Enter the name to be removed? >> a <- getLine >> remove x [] = [] >> print ?Record not found? >> remove x db = >> if x == >> >> >> >> Please let me know! >> >> Thanks a lot >> >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdibaiee at aol.com Mon May 9 14:11:03 2016 From: mdibaiee at aol.com (Mahdi) Date: Mon, 9 May 2016 18:41:03 +0430 Subject: [Haskell-beginners] Fwd: CAF taking all the memory References: <4CACE622-02E7-49F1-AD65-8E7B2936C70B@aol.com> Message-ID: <6D06E900-40D3-4CD1-814D-DA821658D9BD@aol.com> > Begin forwarded message: > > From: Mahdi > Subject: Re: [Haskell-beginners] CAF taking all the memory > Date: May 8, 2016 at 18:06:29 GMT+4:30 > To: Ben Gamari > > Wow, This is a great explanation! Thank you! > I see your point on using lazy lists (although I was not aware of the specific problems you mentioned). > So, I switched over to HMatrix [0], (the libraries you mentioned added a lot of complexity to the code) > which uses unboxed arrays for matrices. > > After refactoring my code to use HMatrix, I ran the program, and the same thing happens, > the speed hasn?t changed much either, then I tried to take another profile to see if anything has changed, > but I couldn?t as described here [1]. > > But my main question is, why would Haskell even store all this data? There are no side-effects, so > there should be no memory leak in my code. > From what I read online, Haskell is trying to avoid re-calculating the functions by caching their > input/outputs (they?re pure, so this can be done), but I hoped there would be a way to disable this, > unfortunately there doesn?t seem to be a way (or there is?). > If that?s the case, then using libraries won?t solve the problem, and that?s frustrating. > > * I also tried compiling with -O0, but no luck. > > [0] http://dis.um.es/~alberto/hmatrix/hmatrixtut.html > [1] https://github.com/albertoruiz/hmatrix/issues/190 > > Thank you Ben! > > - Mahdi > >> On May 3, 2016, at 14:36, Ben Gamari wrote: >> >> Mahdi writes: >> >>> Hello there, >>> >> Hi! >> >>> I?m pretty new to Haskell and I?m trying to write a Neural Network in >>> Haskell for educational purposes. >>> >>> So, I have my neural network working, it can learn XOR in 500 >>> iterations, but the thing is, if I increase the iterations to >>> something like 5 milion times, the process just drains my RAM until >>> either it?s killed or the OS drowns. Here is the code: [0] >>> >>> I searched online and tried to get information on why this is >>> happening, I profiled the memory usage and found that the memory is >>> taken by CAF, searching online, >>> >> Great! The next question you should then ask is "which CAF"? A CAF is >> simply a top-level "constant" in your program. Indeed it sounds like you >> have not defined any cost-centers, which means that GHC will attribute >> the entire cost of your program to the ambiguous cost-center "CAF" >> (which in this case really just means "the whole program"). >> >> As discussed in the users guide [1] one way to define cost-centers >> within your program is to manually annotate expressions with SCC >> pragmas. However, in this case we simply want to let GHC do this for us, >> for which we can use the `-fprof-auto -fprof-cafs` flags (which >> automatically annotate top-level definitions and CAFs with >> cost-centers), >> >> $ ghc -O examples/xor.hs -fprof-auto -fprof-cafs >> >> Now your program should give a much more useful profile (run having set >> the iteration count to 50000), >> >> $ time examples/xor +RTS -p >> [[0.99548584],[4.5138146e-3],[0.9954874],[4.513808e-3]] >> >> real 0m4.019s >> user 0m0.004s >> sys 0m4.013s >> $ cat xor.prof >> Tue May 3 11:15 2016 Time and Allocation Profiling Report (Final) >> >> xor +RTS -p -RTS >> >> total time = 1.11 secs (1107 ticks @ 1000 us, 1 processor) >> total alloc = 1,984,202,600 bytes (excludes profiling overheads) >> >> COST CENTRE MODULE %time %alloc >> >> matrixMap Utils.Math 21.4 26.8 >> matadd Utils.Math 20.8 22.7 >> matmul.\ Utils.Math 10.4 16.0 >> dot Utils.Math 7.1 13.4 >> column Utils.Math 7.0 2.9 >> dot.\ Utils.Math 6.9 1.9 >> rowPairs Utils.Math 5.8 6.5 >> sigmoid' NN 4.7 0.8 >> train.helper Main 4.0 1.3 >> sigmoid NN 3.3 0.8 >> matmul Utils.Math 2.2 2.0 >> hadamard Utils.Math 1.8 2.1 >> columns Utils.Math 1.2 1.3 >> >> individual inherited >> COST CENTRE MODULE no. entries %time %alloc %time %alloc >> >> MAIN MAIN 79 0 0.0 0.0 100.0 100.0 >> [snip] >> CAF:main3 Main 143 0 0.0 0.0 100.0 100.0 >> (...) Main 162 1 0.0 0.0 100.0 100.0 >> train Main 163 1 0.0 0.0 100.0 100.0 >> train.helper Main 164 50001 4.0 1.3 100.0 100.0 >> train.helper.hweights Main 258 50001 0.5 0.0 0.5 0.0 >> train.helper.oweights Main 235 50001 0.4 0.0 0.4 0.0 >> train.helper.oback Main 207 50000 0.3 0.1 19.0 20.9 >> backward' NN 208 50000 0.3 0.6 18.7 20.8 >> [snip] >> >> So, here we see that costs are actually spread throughout the program. >> >> Without diving any deeper into this particular program it's hard to give >> more guidance however I will say that your lazy list Matrix >> representation is very rarely the right choice for even toy linear >> algebra problems. >> >> First, consider the fact that even just a list cons constructor requires >> three words (an info table pointer, a pointer to payload, and a pointer >> to tail) plus the size of the payload (which in the case of an evaluated >> `Float` is 2 words: one info table pointer and the floating point value >> itself). So, a list of n *evaluated* `Float`s (which would require only >> 4*n bytes if packed densely) will require 40*n bytes if represented as a >> lazy list. >> >> Then, consider the fact that indexing into a lazy list is an O(n) >> operation: this means that your `Math.column` operation on an n x m >> matrix may be O(n*m). Even worse, `Math.columns`, as used by >> `Math.matmul` is O(n * m!). >> >> Finally, consider the fact that whenever you "construct" a lazy list you >> aren't actually performing any computation: you are actually >> constructing a single thunk which represents the entire result; however, >> if you then go to index into the middle of that list you will end up >> constructing n cons cells and a thunk for the payload of each. In the >> case of primitive linear algebra operations the cost of constructing >> this payload thunk can be greater than simply computing the result. >> >> For these reasons I wouldn't recommend that lazy lists are used in this >> way. If you have a dense matrix use an array (probably even unboxed; >> see, for instance, the `array`, `vector`, and `repa` libraries); if >> you have a sparse matrix then use an appropriate sparse representation >> (although sadly good sparse linear algebra tools are hard to come by in >> Haskell) Not only will the result be significantly more efficient in >> space and time but the runtime behavior of the program will be >> significantly easier to follow since you can more easily ensure that >> evaluation occurs when you expect it to. >> >> Hopefully this helps. Good luck and let us know if there are further >> issues. >> >> Cheers, >> >> - Ben >> >> >> [1] http://downloads.haskell.org/~ghc/master/users-guide//profiling.html#cost-centres-and-cost-centre-stacks > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Mon May 9 18:50:14 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Mon, 9 May 2016 20:50:14 +0200 Subject: [Haskell-beginners] using HS to writing/managing a selfmade filesystem on a real partition? Message-ID: Mostly all in the title. I have a project of developing a personal filesystem, possibly at first virtual (the file(s) representing a virtual partition formatted with my filesystem, would be saved in a host filesys, eg ext4 or whatever), but probably in the end not virtual, directly working on the contents of a real partition. Can haskell do that kind of thing, aka writing data on a partition directly (without using a known filesys), etc? Is it at least more or less adapted for this task (not talking about performances, unless the consequences be a *really* slow filesys), aka doable, easily doable, relatively speaking (aka not worse than with another language)? Incidentally, if i wanted Linux to recognize the filesys, i've heard one has to write a module and put it in connection with the kernel or something. could haskell do that? if that's a "no" somewhere for one of my questions, which parts can't be written in haskell (without horrible performances or code very very hard to write), and can they be written in C (or whatever) as foreign functions? which parts would that represent for the whole program? Thanks a lot in advance! PS: just in case, tips on sources of information on how to do any of the above will be extremely appreciated! (even if it's in, say C, for that matter, providing there's a way to translate the steps into a haskell program) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sylvain at haskus.fr Mon May 9 21:12:39 2016 From: sylvain at haskus.fr (Sylvain Henry) Date: Mon, 9 May 2016 23:12:39 +0200 Subject: [Haskell-beginners] using HS to writing/managing a selfmade filesystem on a real partition? In-Reply-To: References: Message-ID: Hi, You don't have to write a kernel module (which would better be written in C), you can do everything in userspace and in Haskell with FUSE: https://en.wikipedia.org/wiki/Filesystem_in_Userspace It seems to already have Haskell bindings: https://hackage.haskell.org/package/HFuse-0.2.4.5/docs/System-Fuse.html To implement the file system operations, you can use binary (https://hackage.haskell.org/package/binary), Foreign.Ptr, Data.Bits, etc. You can write data on any real partition by using the associated block devices (e.g., /dev/sda1). Sylvain On 09/05/2016 20:50, Silent Leaf wrote: > Mostly all in the title. > > I have a project of developing a personal filesystem, possibly at > first virtual (the file(s) representing a virtual partition formatted > with my filesystem, would be saved in a host filesys, eg ext4 or > whatever), but probably in the end not virtual, directly working on > the contents of a real partition. > > Can haskell do that kind of thing, aka writing data on a partition > directly (without using a known filesys), etc? Is it at least more or > less adapted for this task (not talking about performances, unless the > consequences be a *really* slow filesys), aka doable, easily doable, > relatively speaking (aka not worse than with another language)? > Incidentally, if i wanted Linux to recognize the filesys, i've heard > one has to write a module and put it in connection with the kernel or > something. could haskell do that? > > if that's a "no" somewhere for one of my questions, which parts can't > be written in haskell (without horrible performances or code very very > hard to write), and can they be written in C (or whatever) as foreign > functions? which parts would that represent for the whole program? > > Thanks a lot in advance! > > PS: just in case, tips on sources of information on how to do any of > the above will be extremely appreciated! (even if it's in, say C, for > that matter, providing there's a way to translate the steps into a > haskell program) > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Tue May 10 18:56:04 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Tue, 10 May 2016 20:56:04 +0200 Subject: [Haskell-beginners] using HS to writing/managing a selfmade filesystem on a real partition? In-Reply-To: References: Message-ID: Thanks! FUSE seems a perfect way to do what I wanna do. Hypothetically, what if I wanted to bypass the Haskell bindings, directly use FUSE in C, but write most of the actual operations in Haskell? AKA, is it possible to call haskell functions/programs *from* C code? And have all individual calls to the Haskell parts be allowed to share private data, rather than being independent, isolated calls? It's just an idea, I figured since writing a fuse filesystem in C doesn't seem too complicated (i found a tutorial, and it just looks like what the Haskell bindings is proposing, except well in theory one has to write everything in C) and i figured perhaps it'd be better/faster, possibly less buggy (the Haskell bindings are tagged experimental, of which i couldn't tell the true interpretation, but which doesn't seem terribly appealing at first sight) to write the FUSE in C, *except* for, well most of the actual "doing something" code, aka the FS operations, which would be written in Haskell. AKA, the final program would start with C, but under the hood use Haskell for most of the meaningful code. This, of course, if such a thing is even possible in the first place! And easily, needless to say. Considering for that matter as I said that the Haskell parts should be able to save private data of its own without having to "start over" the "situation analysis" for each individual call to one of the filesystem operations. Thanks a lot again! Le lundi 9 mai 2016, Sylvain Henry a ?crit : > Hi, > > You don't have to write a kernel module (which would better be written in C), you can do everything in userspace and in Haskell with FUSE: https://en.wikipedia.org/wiki/Filesystem_in_Userspace > It seems to already have Haskell bindings: https://hackage.haskell.org/package/HFuse-0.2.4.5/docs/System-Fuse.html > > To implement the file system operations, you can use binary ( https://hackage.haskell.org/package/binary), Foreign.Ptr, Data.Bits, etc. You can write data on any real partition by using the associated block devices (e.g., /dev/sda1). > > Sylvain > > On 09/05/2016 20:50, Silent Leaf wrote: > > Mostly all in the title. > > I have a project of developing a personal filesystem, possibly at first virtual (the file(s) representing a virtual partition formatted with my filesystem, would be saved in a host filesys, eg ext4 or whatever), but probably in the end not virtual, directly working on the contents of a real partition. > > Can haskell do that kind of thing, aka writing data on a partition directly (without using a known filesys), etc? Is it at least more or less adapted for this task (not talking about performances, unless the consequences be a *really* slow filesys), aka doable, easily doable, relatively speaking (aka not worse than with another language)? > Incidentally, if i wanted Linux to recognize the filesys, i've heard one has to write a module and put it in connection with the kernel or something. could haskell do that? > > if that's a "no" somewhere for one of my questions, which parts can't be written in haskell (without horrible performances or code very very hard to write), and can they be written in C (or whatever) as foreign functions? which parts would that represent for the whole program? > > Thanks a lot in advance! > > PS: just in case, tips on sources of information on how to do any of the above will be extremely appreciated! (even if it's in, say C, for that matter, providing there's a way to translate the steps into a haskell program) > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sylvain at haskus.fr Tue May 10 20:06:52 2016 From: sylvain at haskus.fr (Sylvain Henry) Date: Tue, 10 May 2016 22:06:52 +0200 Subject: [Haskell-beginners] using HS to writing/managing a selfmade filesystem on a real partition? In-Reply-To: References: Message-ID: <643d860e-ce69-889c-e4a6-b43d124e8c9d@haskus.fr> Yes you can call Haskell code from C: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ffi-ghc.html#foreign-export-ghc If you really want to use Haskell, I would go full Haskell to avoid complications (you can update the FUSE bindings if necessary). On the other hand, if you plan to distribute your FS implementation to a non-Haskell audience, maybe it would be better to write it fully in C. On 10/05/2016 20:56, Silent Leaf wrote: > Thanks! FUSE seems a perfect way to do what I wanna do. > > Hypothetically, what if I wanted to bypass the Haskell bindings, > directly use FUSE in C, but write most of the actual operations in > Haskell? > AKA, is it possible to call haskell functions/programs *from* C code? > And have all individual calls to the Haskell parts be allowed to share > private data, rather than being independent, isolated calls? > > It's just an idea, I figured since writing a fuse filesystem in C > doesn't seem too complicated (i found a tutorial, and it just looks > like what the Haskell bindings is proposing, except well in theory one > has to write everything in C) and i figured perhaps it'd be > better/faster, possibly less buggy (the Haskell bindings are tagged > experimental, of which i couldn't tell the true interpretation, but > which doesn't seem terribly appealing at first sight) to write the > FUSE in C, *except* for, well most of the actual "doing something" > code, aka the FS operations, which would be written in Haskell. > > AKA, the final program would start with C, but under the hood use > Haskell for most of the meaningful code. This, of course, if such a > thing is even possible in the first place! And easily, needless to > say. Considering for that matter as I said that the Haskell parts > should be able to save private data of its own without having to > "start over" the "situation analysis" for each individual call to one > of the filesystem operations. > > Thanks a lot again! > > Le lundi 9 mai 2016, Sylvain Henry > a ?crit : > > Hi, > > > > You don't have to write a kernel module (which would better be > written in C), you can do everything in userspace and in Haskell with > FUSE: https://en.wikipedia.org/wiki/Filesystem_in_Userspace > > It seems to already have Haskell bindings: > https://hackage.haskell.org/package/HFuse-0.2.4.5/docs/System-Fuse.html > > > > To implement the file system operations, you can use binary > (https://hackage.haskell.org/package/binary), Foreign.Ptr, Data.Bits, > etc. You can write data on any real partition by using the associated > block devices (e.g., /dev/sda1). > > > > Sylvain > > > > On 09/05/2016 20:50, Silent Leaf wrote: > > > > Mostly all in the title. > > > > I have a project of developing a personal filesystem, possibly at > first virtual (the file(s) representing a virtual partition formatted > with my filesystem, would be saved in a host filesys, eg ext4 or > whatever), but probably in the end not virtual, directly working on > the contents of a real partition. > > > > Can haskell do that kind of thing, aka writing data on a partition > directly (without using a known filesys), etc? Is it at least more or > less adapted for this task (not talking about performances, unless the > consequences be a *really* slow filesys), aka doable, easily doable, > relatively speaking (aka not worse than with another language)? > > Incidentally, if i wanted Linux to recognize the filesys, i've heard > one has to write a module and put it in connection with the kernel or > something. could haskell do that? > > > > if that's a "no" somewhere for one of my questions, which parts > can't be written in haskell (without horrible performances or code > very very hard to write), and can they be written in C (or whatever) > as foreign functions? which parts would that represent for the whole > program? > > > > Thanks a lot in advance! > > > > PS: just in case, tips on sources of information on how to do any of > the above will be extremely appreciated! (even if it's in, say C, for > that matter, providing there's a way to translate the steps into a > haskell program) > > > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Wed May 11 15:41:32 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Wed, 11 May 2016 17:41:32 +0200 Subject: [Haskell-beginners] using HS to writing/managing a selfmade filesystem on a real partition? In-Reply-To: <643d860e-ce69-889c-e4a6-b43d124e8c9d@haskus.fr> References: <643d860e-ce69-889c-e4a6-b43d124e8c9d@haskus.fr> Message-ID: Well I plan on writing an FS with Haskell, aka, both "hardware" handling, (be it in a file (virtual) or on a partition), and filesys operations (read, write, etc). From there, if I wrote the FUSE in C entirely, i'd go with rewriting a ton of code that would be far from easy to duplicate from Haskell. I used to code in C regularly, but I plan on staying in Haskell for the time being. Still, you're right, probably better using the existing bindings. I'll update it if i find bugs, which i hope i won't, I'm not even sure I'd be up to it, but I'm just beginning anyway --and the code doesn seem too heavy. Anyway I'm rambling ^^ Thanks a lot for all those informations! ( And If anyone has good tutorial on FUSE, I'm still interested!) Le mardi 10 mai 2016, Sylvain Henry a ?crit : > Yes you can call Haskell code from C: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ffi-ghc.html#foreign-export-ghc > > If you really want to use Haskell, I would go full Haskell to avoid complications (you can update the FUSE bindings if necessary). On the other hand, if you plan to distribute your FS implementation to a non-Haskell audience, maybe it would be better to write it fully in C. > > > On 10/05/2016 20:56, Silent Leaf wrote: > > Thanks! FUSE seems a perfect way to do what I wanna do. > > Hypothetically, what if I wanted to bypass the Haskell bindings, directly use FUSE in C, but write most of the actual operations in Haskell? > AKA, is it possible to call haskell functions/programs *from* C code? And have all individual calls to the Haskell parts be allowed to share private data, rather than being independent, isolated calls? > > It's just an idea, I figured since writing a fuse filesystem in C doesn't seem too complicated (i found a tutorial, and it just looks like what the Haskell bindings is proposing, except well in theory one has to write everything in C) and i figured perhaps it'd be better/faster, possibly less buggy (the Haskell bindings are tagged experimental, of which i couldn't tell the true interpretation, but which doesn't seem terribly appealing at first sight) to write the FUSE in C, *except* for, well most of the actual "doing something" code, aka the FS operations, which would be written in Haskell. > > AKA, the final program would start with C, but under the hood use Haskell for most of the meaningful code. This, of course, if such a thing is even possible in the first place! And easily, needless to say. Considering for that matter as I said that the Haskell parts should be able to save private data of its own without having to "start over" the "situation analysis" for each individual call to one of the filesystem operations. > > Thanks a lot again! > > Le lundi 9 mai 2016, Sylvain Henry a ?crit : >> Hi, >> >> You don't have to write a kernel module (which would better be written in C), you can do everything in userspace and in Haskell with FUSE: https://en.wikipedia.org/wiki/Filesystem_in_Userspace >> It seems to already have Haskell bindings: https://hackage.haskell.org/package/HFuse-0.2.4.5/docs/System-Fuse.html >> >> To implement the file system operations, you can use binary ( https://hackage.haskell.org/package/binary), Foreign.Ptr, Data.Bits, etc. You can write data on any real partition by using the associated block devices (e.g., /dev/sda1). >> >> Sylvain >> >> On 09/05/2016 20:50, Silent Leaf wrote: >> >> Mostly all in the title. >> >> I have a project of developing a personal filesystem, possibly at first virtual (the file(s) representing a virtual partition formatted with my filesystem, would be saved in a host filesys, eg ext4 or whatever), but probably in the end not virtual, directly working on the contents of a real partition. >> >> Can haskell do that kind of thing, aka writing data on a partition directly (without using a known filesys), etc? Is it at least more or less adapted for this task (not talking about performances, unless the consequences be a *really* slow filesys), aka doable, easily doable, relatively speaking (aka not worse than with another language)? >> Incidentally, if i wanted Linux to recognize the filesys, i've heard one has to write a module and put it in connection with the kernel or something. could haskell do that? >> >> if that's a "no" somewhere for one of my questions, which parts can't be written in haskell (without horrible performances or code very very hard to write), and can they be written in C (or whatever) as foreign functions? which parts would that represent for the whole program? >> >> Thanks a lot in advance! >> >> PS: just in case, tips on sources of information on how to do any of the above will be extremely appreciated! (even if it's in, say C, for that matter, providing there's a way to translate the steps into a haskell program) >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgf.dma at gmail.com Thu May 12 09:16:42 2016 From: sgf.dma at gmail.com (Dmitriy Matrosov) Date: Thu, 12 May 2016 12:16:42 +0300 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: > {-# LANGUAGE DataKinds, GADTs, StandaloneDeriving, Rank2Types, PolyKinds, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, ScopedTypeVariables #-} > > data Nat = Z | S Nat > deriving (Show) On Fri, May 6, 2016 at 2:24 PM, Marcin Mrotek wrote: > You could define SNat as something > newtype SNat (n :: Nat) = SNat Nat > deriving (Show) > to be on the safer side, and then define SNatClass and natVal as something > like: > class SNatClass (n :: Nat) where > singN :: SNat n > > instance SNatClass Z where > singN = SNat Z > > instance SNatClass n => SNatClass (S n) where > singN = SNat (S n) > where SNat n = (singN :: SNat n) > > natVal :: forall n proxy. SNatClass n => proxy n -> Nat > natVal _ = case (singN :: SNat n) of SNat n -> n Hi. Hm.. but such singleton definition differs from mine and i can't get it working. Your singleton defines function `type -> singleton`: *Main> singN :: SNat ('S 'Z) SNat (S Z) and function `type -> Nat`: *Main> natVal (undefined :: SNat ('S 'Z)) S Z Mine singleton: > data SNat2 :: Nat -> * where > SZ :: SNat2 'Z > SN :: SNat2 n -> SNat2 ('S n) > deriving instance Show (SNat2 n) > > class SNatClass2 (a :: Nat) where > singN2 :: SNat2 a > > instance SNatClass2 'Z where > singN2 = SZ > instance SNatClass2 n => SNatClass2 ('S n) where > singN2 = SN singN2 > > natVal2 :: forall p n. SNatClass2 n => p n -> Nat > natVal2 _ = case singN2 :: SNat2 n of > SZ -> Z > SN SZ -> S Z does this too: *Main> singN2 :: SNat2 ('S 'Z) SN SZ *Main> natVal2 (undefined :: SNat2 ('S 'Z)) S Z But mine singleton also defines function `singleton -> type`: *Main> :t SN SZ SN SZ :: SNat2 ('S 'Z) which yours does not: *Main> :t SNat (S Z) SNat (S Z) :: SNat n or in other words: *Main> :t SN SZ :: SNat2 'Z :1:1: Couldn't match type ?'S 'Z? with ?'Z? Expected type: SNat2 'Z Actual type: SNat2 ('S 'Z) In the expression: SN SZ :: SNat2 Z but *Main> :t SNat (S Z) :: SNat 'Z SNat (S Z) :: SNat 'Z :: SNat 'Z Then when i try to define recursive function on singletons, i need that relation: > data Vec :: * -> Nat -> * where > Nil :: Vec a 'Z > Cons :: a -> Vec a n -> Vec a ('S n) > deriving instance Show a => Show (Vec a n) > > natVec2 :: SNat2 n -> Vec Int n > natVec2 SZ = Nil > natVec2 (SN n) = Cons 1 (natVec2 n) as i understand, here (in `natVec2`) pattern matching on value level introduces type equalities (n ~ 'Z) or (n ~ 'S n) at type level correspondingly. But with your singleton it can't be done that way. I've tried to use witness (well, i've probably used it wrong, but still..), but can't figure out how to specify "if (n ~ 'S m), then" at type level: > data SingInst (n :: Nat) where > SingInst :: SNatClass n => SingInst n > > singInst :: forall p n. SNatClass n => p ('S n) -> SingInst n > singInst _ = case (singN :: SNat ('S n)) of > SNat _ -> SingInst > > natVec :: forall p n. SNatClass2 n => p n -> Vec Int n > natVec _ = case (singN :: SNat n) of > SNat Z -> Nil > SNat (S n) -> natVec (singInst (singN :: SNat n)) Is there a way to define `natVec` with your singleton? From marcin.jan.mrotek at gmail.com Fri May 13 10:19:24 2016 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Fri, 13 May 2016 12:19:24 +0200 Subject: [Haskell-beginners] Type depending on value In-Reply-To: References: Message-ID: Hello, Well, yes, singleton defined that way doesn't enforce the value to be equal to the type. Maybe you could use a type class for natVec? It's not a particularly elegant solution, but it's the only one I came up with. Or maybe use two different singleton types, one hidden and only used in SNatClass, and the other exposed and defined the way you did originally? Best regards, Marcin Mrotek -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Sat May 14 21:39:36 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Sat, 14 May 2016 23:39:36 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? Message-ID: All in the title; Since the change in GHC, 7.10 i think, where all Monad instances had to have Applicative instances too, in theory all monads must have a pure method that should be identical to return, right? My subjectively superficial reason for preferring pure (and caring about the issue in the first place) is twofold: shorter (i know, i know, still the shorter, the quicker to read and then understand in the code) and, mostly, less semantically-awkward --honestly the name "stains" the functional semantics in Monadic code, in my opinion, but that's just personal. (For those who know, it feels like the "new" operator in JS (OO class-instanciation semantical imitation)) Of course now I'm perfectly used to, have no trouble seeing it for what it is all the time, not mixing it up with some imperative-like "return" concept. Yet i don't really like it much at all, so I wanted to know to which extent it is safe to always use pure even in explicitly Monadic contexts. Thankx in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidleothomas at gmail.com Sat May 14 21:54:22 2016 From: davidleothomas at gmail.com (David Thomas) Date: Sat, 14 May 2016 14:54:22 -0700 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: As I understand it, that's correct - you can use pure anywhere you'd have used return. On Sat, May 14, 2016 at 2:39 PM, Silent Leaf wrote: > All in the title; Since the change in GHC, 7.10 i think, where all Monad > instances had to have Applicative instances too, in theory all monads must > have a pure method that should be identical to return, right? > > My subjectively superficial reason for preferring pure (and caring about the > issue in the first place) is twofold: shorter (i know, i know, still the > shorter, the quicker to read and then understand in the code) and, mostly, > less semantically-awkward --honestly the name "stains" the functional > semantics in Monadic code, in my opinion, but that's just personal. (For > those who know, it feels like the "new" operator in JS (OO > class-instanciation semantical imitation)) > > Of course now I'm perfectly used to, have no trouble seeing it for what it > is all the time, not mixing it up with some imperative-like "return" > concept. > Yet i don't really like it much at all, so I wanted to know to which extent > it is safe to always use pure even in explicitly Monadic contexts. > > Thankx in advance! > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > From tanuki at gmail.com Sat May 14 22:04:21 2016 From: tanuki at gmail.com (Theodore Lief Gannon) Date: Sat, 14 May 2016 15:04:21 -0700 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: If/when Applicative Do drops, would using 'return' force monad semantics on a do-block that could otherwise be applicative? That's the only thing that comes to mind. Otherwise yeah, I've been using 'pure' exclusively for a while. On May 14, 2016 2:54 PM, "David Thomas" wrote: > As I understand it, that's correct - you can use pure anywhere you'd > have used return. > > On Sat, May 14, 2016 at 2:39 PM, Silent Leaf > wrote: > > All in the title; Since the change in GHC, 7.10 i think, where all Monad > > instances had to have Applicative instances too, in theory all monads > must > > have a pure method that should be identical to return, right? > > > > My subjectively superficial reason for preferring pure (and caring about > the > > issue in the first place) is twofold: shorter (i know, i know, still the > > shorter, the quicker to read and then understand in the code) and, > mostly, > > less semantically-awkward --honestly the name "stains" the functional > > semantics in Monadic code, in my opinion, but that's just personal. (For > > those who know, it feels like the "new" operator in JS (OO > > class-instanciation semantical imitation)) > > > > Of course now I'm perfectly used to, have no trouble seeing it for what > it > > is all the time, not mixing it up with some imperative-like "return" > > concept. > > Yet i don't really like it much at all, so I wanted to know to which > extent > > it is safe to always use pure even in explicitly Monadic contexts. > > > > Thankx in advance! > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcin.jan.mrotek at gmail.com Sun May 15 08:58:46 2016 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Sun, 15 May 2016 10:58:46 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: Hello, > If/when Applicative Do drops, would using 'return' force monad semantics on a do-block that could otherwise be > applicative? That's the only thing that comes to mind. Otherwise yeah, I've been using 'pure' exclusively for a while. I think so, at least until the "Monad of no return" proposal (https://ghc.haskell.org/trac/ghc/wiki/Proposal/MonadOfNoReturn) lands. Best regards, Marcin Mrotek From doug at cs.dartmouth.edu Sun May 15 14:29:34 2016 From: doug at cs.dartmouth.edu (Doug McIlroy) Date: Sun, 15 May 2016 10:29:34 -0400 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? Message-ID: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> > the name [return] "stains" the functional semantics in Monadic code, > in my opinion Amusing. For me, the term "pure" stains monads as impure or diluted. The moral overtones of "pure", as in "purely functional language", drive out more benign interpretatations such as "unadorned". Not a felicitous coinage. Doug McIlroy From silent.leaf0 at gmail.com Sun May 15 15:08:43 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Sun, 15 May 2016 17:08:43 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: that's great news! Thanks to all your answers :) Hope the "no return" proposal gets accepted and incorporated! Le dimanche 15 mai 2016, Marcin Mrotek a ?crit : > Hello, > >> If/when Applicative Do drops, would using 'return' force monad semantics on a do-block that could otherwise be >> applicative? That's the only thing that comes to mind. Otherwise yeah, I've been using 'pure' exclusively for a while. > > I think so, at least until the "Monad of no return" proposal > (https://ghc.haskell.org/trac/ghc/wiki/Proposal/MonadOfNoReturn) > lands. > > Best regards, > Marcin Mrotek > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Sun May 15 15:37:28 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Sun, 15 May 2016 17:37:28 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> References: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> Message-ID: Interesting interpretation! It might not be the one intended, but I always saw "pure" as meaning something like "input just wrapped" (echoing Maybe ofc), "input without effects", i think is the terminology. In other terms, to me "pure", there, is not an absolute description of the "type" of input (especially since the name of a function traditionally mostly defines the output, not the input), as in "non-monadic values are impure", but is a relative description visavis the input, aka, "the output is the undiluted, uneffectful monadic version of the input". Dunno if that was what you meant by "unadorned". In other terms "pure" makes me see the function as a sort of identity that does not dilute or otherwise modify the input value, solely "wraps" it (more or less metaphorically), makes it monadic without modification. I don't see it as meaning that its input values are of a purer "kind" than the corresponding outputs because those latter are (more) monadic. And we can feed monadic values to pure anyway. As for echoing "purely functional language", well ... i don't really see the link (but i might very well miss something), but at any rate isn't it true in the first place (Haskell being pure, barring uses of unsafeStuff/Foreign/etc)? Le dimanche 15 mai 2016, Doug McIlroy a ?crit : > >> the name [return] "stains" the functional semantics in Monadic code, >> in my opinion > > Amusing. For me, the term "pure" stains monads as impure or diluted. > The moral overtones of "pure", as in "purely functional language", > drive out more benign interpretatations such as "unadorned". Not > a felicitous coinage. > > Doug McIlroy > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Sun May 15 15:39:39 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Sun, 15 May 2016 17:39:39 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> Message-ID: Typo, I wrote: > as in "non-monadic values are impure" meant of course > as in "monadic values are impure" Le dimanche 15 mai 2016, Silent Leaf a ?crit : > Interesting interpretation! > It might not be the one intended, but I always saw "pure" as meaning something like "input just wrapped" (echoing Maybe ofc), "input without effects", i think is the terminology. In other terms, to me "pure", there, is not an absolute description of the "type" of input (especially since the name of a function traditionally mostly defines the output, not the input), as in "non-monadic values are impure", but is a relative description visavis the input, aka, "the output is the undiluted, uneffectful monadic version of the input". Dunno if that was what you meant by "unadorned". > In other terms "pure" makes me see the function as a sort of identity that does not dilute or otherwise modify the input value, solely "wraps" it (more or less metaphorically), makes it monadic without modification. I don't see it as meaning that its input values are of a purer "kind" than the corresponding outputs because those latter are (more) monadic. And we can feed monadic values to pure anyway. > > As for echoing "purely functional language", well ... i don't really see the link (but i might very well miss something), but at any rate isn't it true in the first place (Haskell being pure, barring uses of unsafeStuff/Foreign/etc)? > > Le dimanche 15 mai 2016, Doug McIlroy a ?crit : >> >>> the name [return] "stains" the functional semantics in Monadic code, >>> in my opinion >> >> Amusing. For me, the term "pure" stains monads as impure or diluted. >> The moral overtones of "pure", as in "purely functional language", >> drive out more benign interpretatations such as "unadorned". Not >> a felicitous coinage. >> >> Doug McIlroy >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From iustin at k1024.org Sun May 15 21:17:58 2016 From: iustin at k1024.org (Iustin Pop) Date: Sun, 15 May 2016 23:17:58 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> References: <201605151429.u4FETYu5023263@coolidge.cs.Dartmouth.EDU> Message-ID: <20160515211758.GC17355@teal.hq.k1024.org> On 2016-05-15 10:29:34, Doug McIlroy wrote: > > > the name [return] "stains" the functional semantics in Monadic code, > > in my opinion > > Amusing. For me, the term "pure" stains monads as impure or diluted. > The moral overtones of "pure", as in "purely functional language", > drive out more benign interpretatations such as "unadorned". Not > a felicitous coinage. That only happens if we give moral values to such technical terms. And probably happens more often to native English speakers; for me, it's much easier to separate Applicative pure from other meanings of pure. Interesting :) regards, iustin From imantc at gmail.com Sun May 15 22:32:46 2016 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 16 May 2016 00:32:46 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? Message-ID: why not use (%%) as alias for both pure and return? % - as in "investment return" % - as in "pure distilled .. " :-P ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.caught.air at gmail.com Mon May 16 12:18:22 2016 From: i.caught.air at gmail.com (Alex Belanger) Date: Mon, 16 May 2016 08:18:22 -0400 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: (%%) is a binary function. return and pure are both unary. I'm don't see how the infix (%%) is solving anything here. On May 15, 2016 6:32 PM, "Imants Cekusins" wrote: > why not use (%%) as alias for both pure and return? > > % - as in "investment return" > % - as in "pure distilled .. " > > :-P > ? > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From imantc at gmail.com Mon May 16 14:19:55 2016 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 16 May 2016 16:19:55 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: > Alex here is what I tried: (%%):: Applicative f => a -> f a (%%) = pure test::Int -> IO Int test i0 = (%%) $ i0 + (2::Int) seems to work.. I can't get %% to work without () -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.caught.air at gmail.com Mon May 16 14:25:14 2016 From: i.caught.air at gmail.com (Alex Belanger) Date: Mon, 16 May 2016 10:25:14 -0400 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: Correct, you're stuck always writing it with the parenthese because without them; you get an infix function which is binary, not unary. I still don't see what your solution brings new to the table in relevance to the question. It's just trading a poorly named function for arguably an even worse. On May 16, 2016 10:20 AM, "Imants Cekusins" wrote: > > Alex > > here is what I tried: > > (%%):: Applicative f => a -> f a > (%%) = pure > > > test::Int -> IO Int > test i0 = (%%) $ i0 + (2::Int) > > > seems to work.. > > I can't get %% to work without () > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From imantc at gmail.com Mon May 16 14:30:54 2016 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 16 May 2016 16:30:54 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: just an idea. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anfelor at posteo.de Mon May 16 15:08:08 2016 From: anfelor at posteo.de (Anton Felix Lorenzen) Date: Mon, 16 May 2016 17:08:08 +0200 Subject: [Haskell-beginners] can I use "pure" all the time instead of "return" now? In-Reply-To: References: Message-ID: Of course, it doesn't solve anything, but.. {-# LANGUAGE PostfixOperators #-} import Control.Applicative (%%) :: Applicative f => a -> f a (%%) = pure go :: IO Int go = (12 %%) main = do num <- (12 %%) print num From tushar4r at gmail.com Wed May 18 10:24:59 2016 From: tushar4r at gmail.com (Tushar Tyagi) Date: Wed, 18 May 2016 15:54:59 +0530 Subject: [Haskell-beginners] Understanding Monads: Help with 20 Intermediate Haskell Exercises Message-ID: Hi, In order to wrap my head around Applicatives and Monads, I started doing the exercises at http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/ The main class being used for the questions is: class Misty m where banana :: (a -> m b) -> m a -> m b unicorn :: a -> m a furry' :: (a -> b) -> m a -> m b Question #13 asks to create the following function: apple :: (Misty m) => m a -> m (a -> b) -> m b After thinking for around an hour for this, I could not crack it and tried looking at other people's solutions, two of which are: apple = banana . flip furry' apple ma mab = banana (\ab -> furry' ab ma) mab I also tried hoogle to see what this function is in the real world, and the underlying implementation in the source code. Turns out, one of the applicatives uses this flip technique (monads use a different one): (<**>) = liftA2 (flip ($)) Although the code compiles with the solutions, I am still not able to wrap my head around them. For instance, from what I understand from composition, the output of one function becomes the input of the next one. But the input and outputs of these functions vary: banana :: Misty m => (a -> m b) -> m a -> m b flip furry' :: Misty m => m a -> (a -> b) -> m b banana . flip furry' :: Misty m => m a -> m (a -> b) -> m b I am thinking that the entire `(a -> b) -> m b` in flip furry' is being sent to banana as the first argument: (a -> m b), but what happens after that? In the second solution, the types pass, i.e. the lambda is basically furry' which has the type a -> ... -> m b, exactly what is needed in the call to banana. But where will it get the function ab? And how will banana work with the second argument? The definition in the class requires it to be `m a`, but here we are passing it `m a -> m b`. Sorry for such a long post, but I want to understand this wizardry . Thanks, Tushar -------------- next part -------------- An HTML attachment was scrubbed... URL: From imantc at gmail.com Wed May 18 15:58:13 2016 From: imantc at gmail.com (Imants Cekusins) Date: Wed, 18 May 2016 17:58:13 +0200 Subject: [Haskell-beginners] Understanding Monads: Help with 20 Intermediate Haskell Exercises In-Reply-To: References: Message-ID: Hello Tushar, maybe this makes it look a bit clearer: class Misty m where banana:: (f -> m b) -> m f -> m b furry':: (a -> b) -> m a -> m b apple::Misty m => m a -> m (a -> b) -> m b apple ma mf = banana (\f -> furry' f ma) mf in a word: 'a' in banana may be a function f = a -> b ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gesh at gesh.uni.cx Wed May 18 17:10:08 2016 From: gesh at gesh.uni.cx (Gesh) Date: Wed, 18 May 2016 20:10:08 +0300 Subject: [Haskell-beginners] Understanding Monads: Help with 20 Intermediate Haskell Exercises In-Reply-To: References: Message-ID: On 2016-05-18 13:24, Tushar Tyagi wrote: > Hi, > > In order to wrap my head around Applicatives and Monads, I started > doing the > exercises at > http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/ > > The main class being used for the questions is: > |class Misty m where banana :: (a -> m b) -> m a -> m b unicorn :: a -> > m afurry' :: (a -> b) -> m a -> m b Question #13 asks to create the > following function: ||apple :: (Misty m) => m a -> m (a -> b) -> m b |||After thinking for around an hour for this, I could not crack it and > tried looking at other people's solutions, two of which are: | |apple > = banana . flip furry' apple ma mab = banana (\ab -> furry' ab ma) mab || |Note that these two definitions are equivalent, as we may calculate: > banana . flip furry' > = banana . (\x y -> furry' y x) > = \z -> banana ((\x y -> furry' y x) z) > = \z -> banana (\y -> furry' y z) > = \ma -> banana (\ab -> furry' ab ma) So far, we haven't made use of anything about banana and furry' - this calculation works for any pair of functions such that the expression typechecks. However, we only know that the expression has type (a -> b) for some a,b. Suppose we assume that b is a type of form (c -> d), giving the entire expression the type (a -> c -> d). Then we may write: > = \ma mab -> banana (\ab -> furry' ab ma) mab To see this point in another context, consider the function `id x = x`. If we assume that `x :: a -> b` (e.g. by writing the type signature `id :: (a -> b) -> (a -> b)`), then we may also write `id f = \x -> f x`. In our case, we may make this assumption, since banana accepts two arguments. (More formally, `banana :: a -> b -> c` for some a,b,c). | > || > |I also tried hoogle to see what this function is in the real world, > and the underlying implementation in the source code. Turns out, one > of the applicatives uses this flip technique (monads use a different > one): |(<**>) = liftA2 (flip ($)) > |Although the code compiles with the solutions, I am still not able to > wrap my head around them. | This is a good idea in general if you're stuck with these questions. However, it does come with the risk of mistakenly thinking you've found the correct real-world code. This is the case here. Whereas (<**>) and apple have the same type, they have different semantics. Instead, you want `flip ap`. > ap :: (Monad m) => m (a -> b) -> m a -> m b > ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) } It is left as an exercise to the reader to show that, by the desugaring of do-notation as specified in section 3.14 of the Haskell 98 report, we have the following equivalent definition of `apple=flip ap`: > apple mx mf = mf >>= \f -> mx >>= \x -> return (f x) We may then use the definitions: > liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r > liftM f m1 = do { x1 <- m1; return (f x1) } > (=<<) :: Monad m => (a -> m b) -> m a -> m b > f =<< x = x >>= f to obtain: > apple mx mf = mf >>= \f -> mx >>= \x -> return (f x) > = mf >>= \f -> liftM f mx > = flip liftM mx =<< mf Some pointfreeifying gives: > \mx mf -> flip liftM mx =<< mf > = \mx mf -> (=<<) (flip liftM mx) mf > = \mx -> (=<<) (flip liftM mx) > = (=<<) . flip liftM Notice that (=<<) and banana have the same type, and so do liftM and furry', to realize this is the original definition you gave. In contrast, <**> would reduce to (exercise): > mx <**> mf = mx >>= \x -> mf >>= \f -> return (f x) Note that the order of the `mx >>=...` and `mf >>=...` parts is reversed. In general, these might not commute. For example, if `mx=print 1`, `mf=print 2 >>= \_ -> return id`, we'd have that `mx `apple` mf` prints first 2, then 1, whereas `mx <**> mf` prints first 1, then 2. > |For instance, from what I understand from composition, the output of > one function becomes the input of the next one. But the input and > outputs of these functions vary: banana :: Misty m => (a -> m b) -> m > a -> m b flip furry' :: Misty m => m a -> (a -> b) -> m b banana . > flip furry' :: Misty m => m a -> m (a -> b) -> m b | > |I am thinking that the entire `(a -> b) -> m b` in flip furry' ||is being sent to banana as the first argument: (a -> m b), but what > happens after that? | |This is correct. To be completely formal, this is how you show that `banana . flip furry'` has the desired type. (cf. TaPL by Benjamin Pierce) (Note that we drop the Misty m contexts for convenience): > flip :: (a -> b -> c) -> b -> a -> c > -------------------------------------- (T-ARR-ASSOC) > flip :: (a -> b -> c) -> (b -> a -> c) > furry' :: (a -> b) -> m a -> m b > ----------------------------------------------------- (T-APP) > flip furry' :: m a -> (a -> b) -> m b > --------------------------------------- (T-ARR-ASSOC) > flip furry' :: m a -> ((a -> b) -> m b) > > banana :: (a -> m b) -> m a -> m b > ------------------------------------ (T-ARR-ASSOC) > banana :: (a -> m b) -> (m a -> m b) > > (.) :: (b -> c) -> (a -> b) -> a -> c > --------------------------------------------------------------------- (T-INST) > (.) :: ((a -> m b) -> (m a -> m b)) -> (d -> (a -> m b)) -> d -> (m a -> m b) > banana :: (a -> m b) -> (m a -> m b) > ------------------------------------------------- (T-APP) > (.) banana :: (d -> (a -> m b)) -> d -> (m a -> m b) > --------------------------------------------------------------------- (T-INST) > (.) banana :: (m a -> ((a -> b) -> m b)) -> m a -> (m (a -> b) -> m b) > flip furry' :: m a -> ((a -> b) -> m b) > --------------------------------------------------------------------- (T-APP) > (.) banana (flip furry') :: m a -> (m (a -> b) -> m b) > ------------------------------------------------------ (T-ARR-ASSOC') > banana . flip furry' :: m a -> m (a -> b) -> m b Basically, what's going on is that T-APP makes sure that in the expression `f x`, f :: a -> b and x :: a; and T-ARR-ASSOC and T-ARR-ASSOC' allow us to rewrite the type (a -> b -> c) as (a -> (b -> c)) and back. The interesting bit is the occurrences of T-INST. What's going on is that you're applying a polymorphic function at a more specified type. T-INST allows you to instantiate the type variables in a type so as to make stuff line up. This allows us, for example, to write: > idFunc :: (a -> b) -> (a -> b) > idFunc f = id f with the derivation: > id :: a -> a > ------------ (T-INST) > id :: (a -> b) -> (a -> b) > f :: (a -> b) > -------------------------- (T-APP) > id f :: (a -> b) In our case, we have two occurrences of T-INST. Each of them is there in order to make the type variables in (.) line up with the types of banana and furry'. The occurrences are reproduced below: > (.) :: (b -> c) -> (a -> b) -> a -> c > --------------------------------------------------------------------- (T-INST) > (.) :: ((a -> m b) -> (m a -> m b)) -> (d -> (a -> m b)) -> d -> (m a -> m b) > (.) banana :: (d -> (a -> m b)) -> d -> (m a -> m b) > --------------------------------------------------------------------- (T-INST) > (.) banana :: (m a -> ((a -> b) -> m b)) -> m a -> (m (a -> b) -> m b) Note that in order to get (.) banana to be able to get furry' as a parameter, we had to give a the type (a -> b) and d the type m a. Similarly, when we got (.) to be able to get banana as a parameter, we also forced its second parameter to be a binary function. | > |In the second solution, the types pass, i.e. the lambda is basically > furry' which has the type a -> ... -> m b, exactly what is needed in > the call to banana. But where will it get the function ab? And how > will banana work with the second argument? The definition in the class > requires it to be `m a`, but here we are passing it `m a -> m b`. | |In light of the above, you may want to recheck this claim. HTH, Gesh P.S. Sorry if this email is overly long and formal. ||| From mihai.maruseac at gmail.com Wed May 18 23:46:56 2016 From: mihai.maruseac at gmail.com (Mihai Maruseac) Date: Wed, 18 May 2016 19:46:56 -0400 Subject: [Haskell-beginners] ANNOUNCE: Haskell Communities and Activities Report (30th ed., May 2016) Message-ID: On behalf of all the contributors, we are pleased to announce that the Haskell Communities and Activities Report (30th edition, May 2016) is now available, in PDF and HTML formats: http://haskell.org/communities/05-2016/report.pdf http://haskell.org/communities/05-2016/html/report.html All previous editions of HCAR can be accessed on the wiki at https://wiki.haskell.org/Haskell_Communities_and_Activities_Report Many thanks go to all the people that contributed to this report, both directly, by sending in descriptions, and indirectly, by doing all the interesting things that are reported. We hope you will find it as interesting a read as we did. If you have not encountered the Haskell Communities and Activities Reports before, you may like to know that the first of these reports was published in November 2001. Their goal is to improve the communication between the increasingly diverse groups, projects, and individuals working on, with, or inspired by Haskell. The idea behind these reports is simple: Every six months, a call goes out to all of you enjoying Haskell to contribute brief summaries of your own area of work. Many of you respond (eagerly, unprompted, and sometimes in time for the actual deadline) to the call. The editors collect all the contributions into a single report and feed that back to the community. When we try for the next update, six months from now, you might want to report on your own work, project, research area or group as well. So, please put the following into your diaries now: ======================================== End of September 2016: target deadline for contributions to the November 2016 edition of the HCAR Report ======================================== Unfortunately, many Haskellers working on interesting projects are so busy with their work that they seem to have lost the time to follow the Haskell related mailing lists and newsgroups, and have trouble even finding time to report on their work. If you are a member, user or friend of a project so burdened, please find someone willing to make time to report and ask them to "register" with the editors for a simple e-mail reminder in November (you could point us to them as well, and we can then politely ask if they want to contribute, but it might work better if you do the initial asking). Of course, they will still have to find the ten to fifteen minutes to draw up their report, but maybe we can increase our coverage of all that is going on in the community. Feel free to circulate this announcement further in order to reach people who might otherwise not see it. Enjoy! -- Mihai Maruseac (MM) "If you can't solve a problem, then there's an easier problem you can solve: find it." -- George Polya From t_gass at gmx.de Thu May 19 13:12:26 2016 From: t_gass at gmx.de (Tilmann) Date: Thu, 19 May 2016 15:12:26 +0200 Subject: [Haskell-beginners] Code golf Message-ID: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> given: inputA :: IO String inputB :: IO String update :: String -> String -> IO () Is there an elegant way to refactor / code golf this: doIt :: IO () doIt = do a <- inputA b <- inputB update a b liftM2 doesn't work in this case.. Thank you! From imantc at gmail.com Thu May 19 13:22:10 2016 From: imantc at gmail.com (Imants Cekusins) Date: Thu, 19 May 2016 15:22:10 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> Message-ID: if 'update' were changed to update :: [String] -> IO () then you could do: ?doIt :: IO () doIt = sequence [inputA,inputB] >>= update is this better? -------------- next part -------------- An HTML attachment was scrubbed... URL: From t_gass at gmx.de Thu May 19 13:34:17 2016 From: t_gass at gmx.de (Tilmann) Date: Thu, 19 May 2016 15:34:17 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> Message-ID: <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> this is nice, thanks! What if a and b are of different types? I simplified my example to much.. Am 19.05.16 um 15:22 schrieb Imants Cekusins: > if 'update' were changed to > update :: [String] -> IO () > > then you could do: > ?doIt :: IO () > doIt = sequence [inputA,inputB] >>= update > > is this better? > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcin.jan.mrotek at gmail.com Thu May 19 13:37:06 2016 From: marcin.jan.mrotek at gmail.com (Marcin Mrotek) Date: Thu, 19 May 2016 15:37:06 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> Message-ID: Hello, What about "join $ update <$> a <*> b" ? Best regards, Marcin Mrotek -------------- next part -------------- An HTML attachment was scrubbed... URL: From t_gass at gmx.de Thu May 19 14:03:57 2016 From: t_gass at gmx.de (Tilmann) Date: Thu, 19 May 2016 16:03:57 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> Message-ID: <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> That's what I was looking for! I didn't know about join! Thank you! Am 19.05.16 um 15:37 schrieb Marcin Mrotek: > Hello, > > What about "join $ update <$> a <*> b" ? > > Best regards, > Marcin Mrotek > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Fri May 20 02:50:28 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 20 May 2016 04:50:28 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> Message-ID: The interesting bit is, the following function > \? ma mb -> join (pure ? <*> ma <*> mb) which i like to write as follows using ((&) = flip ($)) [infixl 1] > \? ma mb -> pure ? <*> ma <*> mb & join (but it's just personal taste) is very similar to (=<<), aka (flip (>>=)) except the first argument (here ?) has type (a -> b -> m c) instead of (a -> m b), and of course the lambda above takes an added argument too (mb). Some could call it "bind2" (even if it's the flipped version of (>>=) that is being generalized), and well, some do. For those interested, there are several options are available to import it (along possibly with some of its siblings), from several libraries. (List possibly non exhaustive.) http://hackage.haskell.org/package/prelude-generalize-0.4/docs/Prelude-Generalize.html#v:bind2 http://hackage.haskell.org/package/SimpleH-1.2/docs/Algebra-Monad.html#v:bind2 http://hackage.haskell.org/package/definitive-base-2.3/docs/Algebra-Monad-Base.html#v:bind2 your problem become btw then: > doIt = bind2 update a b -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Fri May 20 16:36:20 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 20 May 2016 18:36:20 +0200 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all Message-ID: All in the title! I'm seeking a way to write a console app that isn't just asking questions one line after another with putStr and getLine. More something like Vim or Emacs when they're in the terminal (i don't wanna create a text ed, but it's the kind of programs i'm seeking to write: which takes up all the space on the screen, where you can write at many different places, and keyboard-driven, up to why not mouse- too, if the terminal (and haskell bindings) allow it. So, does anyone know any library to do this? Any tutorial, maybe? I'm seeking for hours, but every time i type stuff like "console application haskell" in google, it just gives me irrelevant answers --as is the trend it seems subjectively, of those last months, with our bestest G-friend. :( thanks a lot in advance for anything! -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.caught.air at gmail.com Fri May 20 16:40:48 2016 From: i.caught.air at gmail.com (Alex Belanger) Date: Fri, 20 May 2016 12:40:48 -0400 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: References: Message-ID: Look at the `vty` library which is similar in essence to (n)curses. It looks you manipulate the terminal's cursor, with different color and modes. I think it even has minimal widgets. On May 20, 2016 12:36 PM, "Silent Leaf" wrote: > All in the title! > > I'm seeking a way to write a console app that isn't just asking questions > one line after another with putStr and getLine. More something like Vim or > Emacs when they're in the terminal (i don't wanna create a text ed, but > it's the kind of programs i'm seeking to write: which takes up all the > space on the screen, where you can write at many different places, and > keyboard-driven, up to why not mouse- too, if the terminal (and haskell > bindings) allow it. > > So, does anyone know any library to do this? Any tutorial, maybe? I'm > seeking for hours, but every time i type stuff like "console application > haskell" in google, it just gives me irrelevant answers --as is the trend > it seems subjectively, of those last months, with our bestest G-friend. :( > > thanks a lot in advance for anything! > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From t_gass at gmx.de Fri May 20 17:15:05 2016 From: t_gass at gmx.de (Tilmann) Date: Fri, 20 May 2016 19:15:05 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> Message-ID: Thank you for the references. I like the term 'bind2'. I had a look at Prelude.Generalized. Wow! bind2 = join .:: liftM2; (.::) = (.) . (.) . (.) Am 20.05.16 um 04:50 schrieb Silent Leaf: > The interesting bit is, the following function > \? ma mb -> join > (pure ? <*> ma <*> mb) which i like to write as follows using ((&) = > flip ($)) [infixl 1] > \? ma mb -> pure ? <*> ma <*> mb & join (but > it's just personal taste) is very similar to (=<<), aka (flip (>>=)) > except the first argument (here ?) has type (a -> b -> m c) instead of > (a -> m b), and of course the lambda above takes an added argument too > (mb). Some could call it "bind2" (even if it's the flipped version of > (>>=) that is being generalized), and well, some do. For those > interested, there are several options are available to import it > (along possibly with some of its siblings), from several libraries. > (List possibly non exhaustive.) > http://hackage.haskell.org/package/prelude-generalize-0.4/docs/Prelude-Generalize.html#v:bind2 > http://hackage.haskell.org/package/SimpleH-1.2/docs/Algebra-Monad.html#v:bind2 > http://hackage.haskell.org/package/definitive-base-2.3/docs/Algebra-Monad-Base.html#v:bind2 > your problem become btw then: > doIt = bind2 update a b > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From fa-ml at ariis.it Fri May 20 17:11:43 2016 From: fa-ml at ariis.it (Francesco Ariis) Date: Fri, 20 May 2016 19:11:43 +0200 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: References: Message-ID: <20160520171143.GA29944@casa.casa> On Fri, May 20, 2016 at 06:36:20PM +0200, Silent Leaf wrote: > All in the title! > > I'm seeking a way to write a console app that isn't just asking questions > one line after another with putStr and getLine. More something like Vim or > Emacs when they're in the terminal (i don't wanna create a text ed, but > it's the kind of programs i'm seeking to write: which takes up all the > space on the screen, where you can write at many different places, and > keyboard-driven, up to why not mouse- too, if the terminal (and haskell > bindings) allow it. I suppose ncurses [1] would do, or other curses packages! [1] https://hackage.haskell.org/package/ncurses From silent.leaf0 at gmail.com Fri May 20 19:09:32 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 20 May 2016 21:09:32 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> Message-ID: yes, this definition of bind2 looks kinda "frightening". if fact it's simpler than it looks: (.::) merely takes two functions, then the three next parameters applied to the result of this special composition, will be applied to the second parameter, before the result be given as input for the first parameter. it must be compared with (.), which only allows the second function to get one single parameter, before the result of this application becomes the first parameter of the first function of the composition, after which any supplementary parameter applied to the whole will go to the left function: > (left . right) a b c d e = left (right a) b c d e By comparison: > (left .:: right) a b c d e = left (right a b c) d e in the first equation above, defining (.), let's say `right` has type a -> b -> c -> d. then `left` will get as first parameter, a partial function, aka (right a :: b -> c -> d). but, in the second equation, `right` gets all of its three parameters (a, b and c), returning a value of type `d`, before `left` gets said result-value as its own first parameter, and then possibly get other parameters of its own (here, d and e). thus with bind2: bind2 f ma mb = (join .:: liftM2) f ma mb = join (liftM2 f ma mb) Now, in my opinion, the point-free style definition of (.::), aka composition of (.) with itself, three time, is way overkill (better use a lambda to clarify the purpose), but maybe is it better in terms of performance or whatever. it's certainly shorter, and when you know what it entails, it's simple, but it can easily frighten anyone else. if one wants to understand this (subjectively overkill) point-free definition, (.::) = (.) . (.) .(.) better do the opposite action that leads to point free style, aka, better name and reveal variables. To make it more readable, i'll define first: dot = (.) f .:: g = (dot . dot . dot) f g = (dot . dot) (dot f) g = (dot . dot) (f .) g = dot (dot (f .)) g = dot ((f .).) g = ((f . ) .) . g this expansion (or whatever you call it), solely uses the basic rule (a . b) c = a (b c), or, with "pollution" around, (w . a . b) c d = (w . a) (b c) d = w (a (b c)) d. in the case of b = dot = (.), and c = f, you get (dot f) = (f .), aka, partially applied composition of f with "something" (the implicit parameter). now, this weird ((f .) .) . g = f .:: g is as we said, directly equivalent to \f g a b c -> f (g a b c) indeed: > f .:: g > = (((f .) .) . g) a b c -- structure equivalent to (x.g) a b c > = ((f .) .) (g a) b c -- to (w .) (g a) b c [with x = (w.) and w = (f .)] > = ((f .) . (g a)) b c -- to (w . (g a)) b c = (w . v) a b > = (f .) ((g a) b) c -- to (f.) (v b) c = (f.) (g a b) c -- as v = g a > = (f . (g a b)) c -- to (f . k) c [with k = (g a b)] > = f ((g a b) c) = f (g a b c) -- to f (k c) which is what we thought (.::) was. simply put, every dot in > (((f .) .) . g) a b c will allow, first, with the dot to the right, that g, as right side of a function composition, take the first argument that follows (here a), becoming a binary partial app (g a); > ((f .) . (g a)) b c -- first dot was used then, this binary partial app (g a) being now the right side of another composition (second, aka middle dot), will get a new argument of its own (b), making it an unary partial app (g a b) > (f . (g a b)) c -- second dot was used and the last dot the the extreme left, at last, allows (g a b) to take its last argument before finally the result be inputed to the function f: > f (g a b c) I hope it clarifies everything for anyone interested and that didn't know it already, of course. Le vendredi 20 mai 2016, Tilmann a ?crit : > Thank you for the references. I like the term 'bind2'. I had a look at Prelude.Generalized. Wow! > > bind2 = join .:: liftM2; > (.::) = (.) . (.) . (.) > > Am 20.05.16 um 04:50 schrieb Silent Leaf: > > The interesting bit is, the following function > \? ma mb -> join (pure ? <*> ma <*> mb) which i like to write as follows using ((&) = flip ($)) [infixl 1] > \? ma mb -> pure ? <*> ma <*> mb & join (but it's just personal taste) is very similar to (=<<), aka (flip (>>=)) except the first argument (here ?) has type (a -> b -> m c) instead of (a -> m b), and of course the lambda above takes an added argument too (mb). Some could call it "bind2" (even if it's the flipped version of (>>=) that is being generalized), and well, some do. For those interested, there are several options are available to import it (along possibly with some of its siblings), from several libraries. (List possibly non exhaustive.) http://hackage.haskell.org/package/prelude-generalize-0.4/docs/Prelude-Generalize.html#v:bind2 http://hackage.haskell.org/package/SimpleH-1.2/docs/Algebra-Monad.html#v:bind2 http://hackage.haskell.org/package/definitive-base-2.3/docs/Algebra-Monad-Base.html#v:bind2 your problem become btw then: > doIt = bind2 update a b > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Fri May 20 19:13:53 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 20 May 2016 21:13:53 +0200 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: <20160520171143.GA29944@casa.casa> References: <20160520171143.GA29944@casa.casa> Message-ID: thanks a lot! will look into it then get back to you. :) it looks promising! Le vendredi 20 mai 2016, Francesco Ariis a ?crit : > On Fri, May 20, 2016 at 06:36:20PM +0200, Silent Leaf wrote: >> All in the title! >> >> I'm seeking a way to write a console app that isn't just asking questions >> one line after another with putStr and getLine. More something like Vim or >> Emacs when they're in the terminal (i don't wanna create a text ed, but >> it's the kind of programs i'm seeking to write: which takes up all the >> space on the screen, where you can write at many different places, and >> keyboard-driven, up to why not mouse- too, if the terminal (and haskell >> bindings) allow it. > > I suppose ncurses [1] would do, or other curses packages! > > [1] https://hackage.haskell.org/package/ncurses > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjaminfjones at gmail.com Fri May 20 19:17:42 2016 From: benjaminfjones at gmail.com (Benjamin Jones) Date: Fri, 20 May 2016 12:17:42 -0700 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: References: <20160520171143.GA29944@casa.casa> Message-ID: On Fri, May 20, 2016 at 12:13 PM, Silent Leaf wrote: > thanks a lot! will look into it then get back to you. :) it looks > promising! > > Le vendredi 20 mai 2016, Francesco Ariis a ?crit : > > On Fri, May 20, 2016 at 06:36:20PM +0200, Silent Leaf wrote: > >> All in the title! > >> > >> I'm seeking a way to write a console app that isn't just asking > questions > >> one line after another with putStr and getLine. More something like Vim > or > >> Emacs when they're in the terminal (i don't wanna create a text ed, but > >> it's the kind of programs i'm seeking to write: which takes up all the > >> space on the screen, where you can write at many different places, and > >> keyboard-driven, up to why not mouse- too, if the terminal (and haskell > >> bindings) allow it. > > > > I suppose ncurses [1] would do, or other curses packages! > > > > [1] https://hackage.haskell.org/package/ncurses > I strongly recommend 'brick' [2]. It is very well engineered and documented. It will be much higher level than the interface provided by ncurses. [2] https://hackage.haskell.org/package/brick -- Benjamin Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From bergey at alum.mit.edu Fri May 20 19:48:36 2016 From: bergey at alum.mit.edu (Daniel Bergey) Date: Fri, 20 May 2016 15:48:36 -0400 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: References: Message-ID: <87zirky0h7.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> In addition to vty, here are a couple of higher-level (I think) libraries in the same vein: http://hackage.haskell.org/package/concurrent-output http://hackage.haskell.org/package/brick On 2016-05-20 at 12:40, Alex Belanger wrote: > Look at the `vty` library which is similar in essence to (n)curses. > > It looks you manipulate the terminal's cursor, with different color and modes. > > I think it even has minimal widgets. > > On May 20, 2016 12:36 PM, "Silent Leaf" wrote: > > All in the title! > > I'm seeking a way to write a console app that isn't just asking questions one line > after another with putStr and getLine. More something like Vim or Emacs when they're > in the terminal (i don't wanna create a text ed, but it's the kind of programs i'm > seeking to write: which takes up all the space on the screen, where you can write at > many different places, and keyboard-driven, up to why not mouse- too, if the > terminal (and haskell bindings) allow it. > > So, does anyone know any library to do this? Any tutorial, maybe? I'm seeking for > hours, but every time i type stuff like "console application haskell" in google, it > just gives me irrelevant answers --as is the trend it seems subjectively, of those > last months, with our bestest G-friend. :( > > thanks a lot in advance for anything! > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners From silent.leaf0 at gmail.com Fri May 20 21:37:03 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Fri, 20 May 2016 23:37:03 +0200 Subject: [Haskell-beginners] How to write console apps? Can't find any library, tutorial... at all In-Reply-To: <87zirky0h7.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> References: <87zirky0h7.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: great thanks! yeah higher lever is possibly better i think here :) i'll compare and try a bit of all :) Thanks again! Le vendredi 20 mai 2016, Daniel Bergey a ?crit : > In addition to vty, here are a couple of higher-level (I think) > libraries in the same vein: > > http://hackage.haskell.org/package/concurrent-output > http://hackage.haskell.org/package/brick > > On 2016-05-20 at 12:40, Alex Belanger wrote: >> Look at the `vty` library which is similar in essence to (n)curses. >> >> It looks you manipulate the terminal's cursor, with different color and modes. >> >> I think it even has minimal widgets. >> >> On May 20, 2016 12:36 PM, "Silent Leaf" wrote: >> >> All in the title! >> >> I'm seeking a way to write a console app that isn't just asking questions one line >> after another with putStr and getLine. More something like Vim or Emacs when they're >> in the terminal (i don't wanna create a text ed, but it's the kind of programs i'm >> seeking to write: which takes up all the space on the screen, where you can write at >> many different places, and keyboard-driven, up to why not mouse- too, if the >> terminal (and haskell bindings) allow it. >> >> So, does anyone know any library to do this? Any tutorial, maybe? I'm seeking for >> hours, but every time i type stuff like "console application haskell" in google, it >> just gives me irrelevant answers --as is the trend it seems subjectively, of those >> last months, with our bestest G-friend. :( >> >> thanks a lot in advance for anything! >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > -------------- next part -------------- An HTML attachment was scrubbed... URL: From t_gass at gmx.de Sat May 21 14:03:50 2016 From: t_gass at gmx.de (Tilmann) Date: Sat, 21 May 2016 16:03:50 +0200 Subject: [Haskell-beginners] Code golf In-Reply-To: References: <875d19ea-7524-37ad-b475-68c7f4a36dd1@gmx.de> <856d279c-1e01-228a-0dcc-451578f7e2f8@gmx.de> <1b168c3f-d5b6-208c-8862-d9749e11e361@gmx.de> Message-ID: <945a8287-ddd0-4ef6-d105-a975a31dc27f@gmx.de> Thank you so much! That was very enlightening! Am 20.05.16 um 21:09 schrieb Silent Leaf: > yes, this definition of bind2 looks kinda "frightening". if fact it's > simpler than it looks: (.::) merely takes two functions, then the > three next parameters applied to the result of this special > composition, will be applied to the second parameter, before the > result be given as input for the first parameter. > > it must be compared with (.), which only allows the second function to > get one single parameter, before the result of this application > becomes the first parameter of the first function of the composition, > after which any supplementary parameter applied to the whole will go > to the left function: > > (left . right) a b c d e = left (right a) b c d e > By comparison: > > (left .:: right) a b c d e = left (right a b c) d e > > in the first equation above, defining (.), let's say `right` has type > a -> b -> c -> d. then `left` will get as first parameter, a partial > function, aka (right a :: b -> c -> d). but, in the second equation, > `right` gets all of its three parameters (a, b and c), returning a > value of type `d`, before `left` gets said result-value as its own > first parameter, and then possibly get other parameters of its own > (here, d and e). > > thus with bind2: > bind2 f ma mb = (join .:: liftM2) f ma mb = join (liftM2 f ma mb) > > Now, in my opinion, the point-free style definition of (.::), aka > composition of (.) with itself, three time, is way overkill (better > use a lambda to clarify the purpose), but maybe is it better in terms > of performance or whatever. it's certainly shorter, and when you know > what it entails, it's simple, but it can easily frighten anyone else. > > if one wants to understand this (subjectively overkill) point-free > definition, > (.::) = (.) . (.) .(.) > better do the opposite action that leads to point free style, aka, > better name and reveal variables. To make it more readable, i'll > define first: > dot = (.) > f .:: g = (dot . dot . dot) f g > = (dot . dot) (dot f) g > = (dot . dot) (f .) g > = dot (dot (f .)) g > = dot ((f .).) g > = ((f . ) .) . g > this expansion (or whatever you call it), solely uses the basic rule > (a . b) c = a (b c), or, with "pollution" around, (w . a . b) c d = (w > . a) (b c) d = w (a (b c)) d. > in the case of b = dot = (.), and c = f, you get (dot f) = (f .), aka, > partially applied composition of f with "something" (the implicit > parameter). > > now, this weird > ((f .) .) . g = f .:: g > is as we said, directly equivalent to > \f g a b c -> f (g a b c) > indeed: > > f .:: g > > = (((f .) .) . g) a b c -- structure equivalent to (x.g) a b c > > = ((f .) .) (g a) b c -- to (w .) (g a) b c [with x = (w.) and w > = (f .)] > > = ((f .) . (g a)) b c -- to (w . (g a)) b c = (w . v) a b > > = (f .) ((g a) b) c -- to (f.) (v b) c = (f.) (g a b) c -- as v > = g a > > = (f . (g a b)) c -- to (f . k) c [with k = (g a b)] > > = f ((g a b) c) = f (g a b c) -- to f (k c) > which is what we thought (.::) was. > simply put, every dot in > > (((f .) .) . g) a b c > will allow, first, with the dot to the right, that g, as right side of > a function composition, take the first argument that follows (here a), > becoming a binary partial app (g a); > > ((f .) . (g a)) b c -- first dot was used > then, this binary partial app (g a) being now the right side of > another composition (second, aka middle dot), will get a new argument > of its own (b), making it an unary partial app (g a b) > > (f . (g a b)) c -- second dot was used > and the last dot the the extreme left, at last, allows (g a b) to take > its last argument before finally the result be inputed to the function f: > > f (g a b c) > > I hope it clarifies everything for anyone interested and that didn't > know it already, of course. > > > > Le vendredi 20 mai 2016, Tilmann > a ?crit : > > Thank you for the references. I like the term 'bind2'. I had a look > at Prelude.Generalized. Wow! > > > > bind2 = join .:: liftM2; > > (.::) = (.) . (.) . (.) > > > > Am 20.05.16 um 04:50 schrieb Silent Leaf: > > > > The interesting bit is, the following function > \? ma mb -> join > (pure ? <*> ma <*> mb) which i like to write as follows using ((&) = > flip ($)) [infixl 1] > \? ma mb -> pure ? <*> ma <*> mb & join (but > it's just personal taste) is very similar to (=<<), aka (flip (>>=)) > except the first argument (here ?) has type (a -> b -> m c) instead of > (a -> m b), and of course the lambda above takes an added argument too > (mb). Some could call it "bind2" (even if it's the flipped version of > (>>=) that is being generalized), and well, some do. For those > interested, there are several options are available to import it > (along possibly with some of its siblings), from several libraries. > (List possibly non exhaustive.) > http://hackage.haskell.org/package/prelude-generalize-0.4/docs/Prelude-Generalize.html#v:bind2 > http://hackage.haskell.org/package/SimpleH-1.2/docs/Algebra-Monad.html#v:bind2 > http://hackage.haskell.org/package/definitive-base-2.3/docs/Algebra-Monad-Base.html#v:bind2 > your problem become btw then: > doIt = bind2 update a b > > > > _______________________________________________ > > Beginners mailing list > > Beginners at haskell.org > > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > > > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Mon May 23 16:06:52 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Mon, 23 May 2016 18:06:52 +0200 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? Message-ID: Hi! I'm still studying the theory of Haskell, but i also wanted to start dabbling with guideless coding, all by myself, and it happens experience is just as much important as theoretical knowledge! I'm not surprise mind you :P Say there's a class, many types that can instantiate it. Then, i in fact need to be able to concatenate (mappend would be ideal!), make lists of values of different types, all instantiating the class. I'm a bit lost on this. There are at least two sorts of ways to handle said group of types, but i'm not certain either is best, and i'm not even very much satisfied about either. Plus they don't specifically differ as regards handling of listing or otherwise interacting *between* different instances of the same class (or alternately, different types born from the same Type constructor). First idea i had, was based on making a class indeed, as well i just love this type of polymorphism (visavis other paradigms). Each type would only have to instantiate the key metshods, and no need of wrappers to use said methods, so on this respect it's pretty great. However, as soon as we want operations between values of different types, it rather gets tricky. The only way i know of to make a heterogeneous list is to use ExistentialQuantificators, create a newtype (or data?) wrapper for the class, allowing for any type to be in, without parameters. Now, the problem i have with this, is the wrapping: if i wanna make a list of types, i gotta wrap all values, and if this list becomes member of a superlist of the same polymorphic type, i gotta wrap this very sublist again with the "class wrapper". Maybe i'm imagining problems and i won't actually need to touch too much to the wrapping if i write the correct functions or instances, but from where i am, permanent wrapping seems tiresome, very much in fact removes the purpose of a class: to allow polymorphic functions without need to wrap the types of inputs/outputs inside a newtype. Which lead me to the second solution: forget the class, and make a type constructor that basically gets a list of key-methods and one field for the wrapped type. Basically it amounts to OOP, at least it seems so. I'm not really a big fan of the thing, and eventually i realized it wouldn't help me more visavis trans-type methods, especially an idea of one or more monoidal instances for the class, or the type constructor that replaces it. (Actually I'm not wholly certain as of how I'm supposed to handle Type constructors instead of classes, as I only know how to make heterogeneous out of a class, not out of a type constructor, even if its polymorphic key-methods are fields included in it. (hope i'm being clear enough, don't hesitate telling me otherwise!) So, as I'm kinda beginner as regards actual coding, i'm asking advice on the subject. Maybe the problem is in how i look at the problem, and I shouldn't even be there trying to do what i try to do. Any alternative solution or viewpoint is heartily welcome! I resume my problem once more: how to handle cross-type interactions and grouping when they only have a class in common, and if possible without having to use ExistentialQuantificators, unless there's a way to keep the wrappers far away, invisible, automatic. Thanks a lot in advance! (Ideas of specialized tutorials are also very much welcome!) -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Mon May 23 16:21:30 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Mon, 23 May 2016 18:21:30 +0200 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: References: Message-ID: By the way if anyone knows the price on performances and any other technical or non-obvious price that one must pay while using ExistentialQuantificators, esp to make heterogeneous types then lists? On the subject of all those half-extensions half-hacks (?) i sometimes really hesitate, fearing some optimisations will suddenly disappear just because of one or two bad uses of those extensions or another. In fact with my problem i have the distinct intuition that it seems really absurd to have to use extensions of the basic haskell just to solve a situation that to me seems very possibly usual, or at least far from rare. I keep thinking I took the problem wrongly, or I'm just not seeking to do the right thing, but so far zippo... -------------- next part -------------- An HTML attachment was scrubbed... URL: From imantc at gmail.com Mon May 23 20:03:53 2016 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 23 May 2016 22:03:53 +0200 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: References: Message-ID: for me a rule of thumb for choosing features / extensions is: if I see compiler errors, I should understand them and know how to fix them. ? Parameterized types, type sinonyms, records and classes with as few extensions as possible are pretty much all I use, type wise. You can do a lot with them alone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cezar.elnazli2 at gmail.com Mon May 23 20:26:27 2016 From: cezar.elnazli2 at gmail.com (Cezar Elnazli) Date: Mon, 23 May 2016 23:26:27 +0300 Subject: [Haskell-beginners] All About Monads Message-ID: <469C3C72-7ABF-4B8F-B676-C4D3771E4D0C@gmail.com> Hello, I am currently going through "All About Monads" on the Haskell Wiki. I see that it also has a Github repository[1]. However, the repository seems outdated to the point where the Makefile no longer works (I was not able to build the wiki), some (if not most) of the examples no longer compile, or they do so with warnings (e.g. example12.hs), and even the formatting of the published article on the wiki seems broken. What I'm asking is if the repository I mentioned is the correct one, and if it makes any sense to send a pull request or if it is worth the effort to fork it and update the code. Thanks! [1]: https://github.com/dag/all-about-monads From imantc at gmail.com Mon May 23 20:40:43 2016 From: imantc at gmail.com (Imants Cekusins) Date: Mon, 23 May 2016 22:40:43 +0200 Subject: [Haskell-beginners] All About Monads In-Reply-To: <469C3C72-7ABF-4B8F-B676-C4D3771E4D0C@gmail.com> References: <469C3C72-7ABF-4B8F-B676-C4D3771E4D0C@gmail.com> Message-ID: https://wiki.haskell.org/All_About_Monads says: If you wish to help out you should fork this GitHub repo rather than edit this page, for now. ? or you could add issues here: https://github.com/dag/all-about-monads/issues -------------- next part -------------- An HTML attachment was scrubbed... URL: From bergey at alum.mit.edu Tue May 24 20:15:13 2016 From: bergey at alum.mit.edu (Daniel Bergey) Date: Tue, 24 May 2016 16:15:13 -0400 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: References: Message-ID: <87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> On 2016-05-23 at 12:06, Silent Leaf wrote: > Say there's a class, many types that can instantiate it. Then, i in fact need to be able > to concatenate (mappend would be ideal!), make lists of values of different types, all > instantiating the class. In most cases, when Haskell beginners want to make a list that contains several types from a single type class, there's a better way to organize the code. If you post your code, I'll try to suggest a specific solution. In general, try to find a simple data type that captures the same fields & functions as an unknown type that is part of the type class. Here's an example. We have a type class for vectors in a metric space, and instances for 2D, 3D, etc. > class Metric v where > length :: v -> Double > (*^) :: Double -> v -> v This class has the law: s * length v == length (s *^ v) Instead of a heterogeneous list [ V2 1 2, V3 3 4 5, V4 6 7 8 9], we make a list that just has the length of each vector, and lets us multiply those lengths by a scalar. In this case, we don't even need to write a new data type, the type is simply Double. We can write: > [ length (V2 1 2), length (V3 3 4 5), length (V4 6 7 8 9) ] And (*) gives us what Metric does with (*^). Of course, with your class, it's probably not so obvious how to transform the class this way. It's certainly possible to make a record with functions as members, moving in the object-oriented direction. Existential types (with a class constraint inside the data constructor) are even more rarely used. cheers, bergey From silent.leaf0 at gmail.com Thu May 26 13:44:51 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Thu, 26 May 2016 15:44:51 +0200 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: <87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> References: <87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: I understand your example. Still it's useless if we need the value of the multiplied vectors, more than just a list of their lengths after the operation, unless i missed something. At any rate; I'm trying to create a representation of mathematical sets. The tricky part being, they're precisely capable to handle any kind of content, including themselves. But I think I went too overboard, trying to handle the idea of sets that could contain strictly any type (at once). In practice, the basic elements will be rather similar, and known enough at least so that I can merely use ADTs for the various "types" of elements, and same for sets themselves. If needed I can create two instances of monoids, one for And, one for Or, using newtype wrappers. It's vaguely a hassle but anyway it'll only be useful if i have to create functions that could work on both monoids (separately), which would be interesting enough so i don't merely duplicate the job. There's also the possibility i need to use existing functions already using monoids... For now I think i'll be ok with ADTs and one common wrapper for all elements. Thanks still, I'll think about your idea, it's rather interesting. Le mardi 24 mai 2016, Daniel Bergey a ?crit : > On 2016-05-23 at 12:06, Silent Leaf wrote: >> Say there's a class, many types that can instantiate it. Then, i in fact need to be able >> to concatenate (mappend would be ideal!), make lists of values of different types, all >> instantiating the class. > > In most cases, when Haskell beginners want to make a list that contains > several types from a single type class, there's a better way to organize > the code. If you post your code, I'll try to suggest a specific > solution. > > In general, try to find a simple data type that captures the same fields > & functions as an unknown type that is part of the type class. Here's > an example. > > We have a type class for vectors in a metric space, and instances for > 2D, 3D, etc. > >> class Metric v where >> length :: v -> Double >> (*^) :: Double -> v -> v > > This class has the law: s * length v == length (s *^ v) > > Instead of a heterogeneous list [ V2 1 2, V3 3 4 5, V4 6 7 8 9], we make > a list that just has the length of each vector, and lets us multiply > those lengths by a scalar. In this case, we don't even need to write a > new data type, the type is simply Double. We can write: > >> [ length (V2 1 2), length (V3 3 4 5), length (V4 6 7 8 9) ] > > And (*) gives us what Metric does with (*^). Of course, with your > class, it's probably not so obvious how to transform the class this way. > > It's certainly possible to make a record with functions as members, > moving in the object-oriented direction. Existential types (with a > class constraint inside the data constructor) are even more rarely used. > > cheers, > bergey > -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.caught.air at gmail.com Thu May 26 13:53:57 2016 From: i.caught.air at gmail.com (Alex Belanger) Date: Thu, 26 May 2016 09:53:57 -0400 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: References: <87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Monoid would fit the picture as far as "concatenating" the same type go. What you could do is have constructors that defines which types can be concatenated together then only that wrapper type implements the final Monoid instance. On May 26, 2016 9:44 AM, "Silent Leaf" wrote: I understand your example. Still it's useless if we need the value of the multiplied vectors, more than just a list of their lengths after the operation, unless i missed something. At any rate; I'm trying to create a representation of mathematical sets. The tricky part being, they're precisely capable to handle any kind of content, including themselves. But I think I went too overboard, trying to handle the idea of sets that could contain strictly any type (at once). In practice, the basic elements will be rather similar, and known enough at least so that I can merely use ADTs for the various "types" of elements, and same for sets themselves. If needed I can create two instances of monoids, one for And, one for Or, using newtype wrappers. It's vaguely a hassle but anyway it'll only be useful if i have to create functions that could work on both monoids (separately), which would be interesting enough so i don't merely duplicate the job. There's also the possibility i need to use existing functions already using monoids... For now I think i'll be ok with ADTs and one common wrapper for all elements. Thanks still, I'll think about your idea, it's rather interesting. Le mardi 24 mai 2016, Daniel Bergey a ?crit : > On 2016-05-23 at 12:06, Silent Leaf wrote: >> Say there's a class, many types that can instantiate it. Then, i in fact need to be able >> to concatenate (mappend would be ideal!), make lists of values of different types, all >> instantiating the class. > > In most cases, when Haskell beginners want to make a list that contains > several types from a single type class, there's a better way to organize > the code. If you post your code, I'll try to suggest a specific > solution. > > In general, try to find a simple data type that captures the same fields > & functions as an unknown type that is part of the type class. Here's > an example. > > We have a type class for vectors in a metric space, and instances for > 2D, 3D, etc. > >> class Metric v where >> length :: v -> Double >> (*^) :: Double -> v -> v > > This class has the law: s * length v == length (s *^ v) > > Instead of a heterogeneous list [ V2 1 2, V3 3 4 5, V4 6 7 8 9], we make > a list that just has the length of each vector, and lets us multiply > those lengths by a scalar. In this case, we don't even need to write a > new data type, the type is simply Double. We can write: > >> [ length (V2 1 2), length (V3 3 4 5), length (V4 6 7 8 9) ] > > And (*) gives us what Metric does with (*^). Of course, with your > class, it's probably not so obvious how to transform the class this way. > > It's certainly possible to make a record with functions as members, > moving in the object-oriented direction. Existential types (with a > class constraint inside the data constructor) are even more rarely used. > > cheers, > bergey > _______________________________________________ Beginners mailing list Beginners at haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Thu May 26 15:20:13 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Thu, 26 May 2016 17:20:13 +0200 Subject: [Haskell-beginners] How to best handle classes of types, interactions and listing of different types? In-Reply-To: References: <87r3crxlf2.fsf@chladni.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Hey, not a bad idea at all! I'll think about it, thanks! Le jeudi 26 mai 2016, Alex Belanger a ?crit : > Monoid would fit the picture as far as "concatenating" the same type go. What you could do is have constructors that defines which types can be concatenated together then only that wrapper type implements the final Monoid instance. > > On May 26, 2016 9:44 AM, "Silent Leaf" wrote: > > I understand your example. Still it's useless if we need the value of the multiplied vectors, more than just a list of their lengths after the operation, unless i missed something. > > At any rate; I'm trying to create a representation of mathematical sets. The tricky part being, they're precisely capable to handle any kind of content, including themselves. But I think I went too overboard, trying to handle the idea of sets that could contain strictly any type (at once). In practice, the basic elements will be rather similar, and known enough at least so that I can merely use ADTs for the various "types" of elements, and same for sets themselves. > If needed I can create two instances of monoids, one for And, one for Or, using newtype wrappers. It's vaguely a hassle but anyway it'll only be useful if i have to create functions that could work on both monoids (separately), which would be interesting enough so i don't merely duplicate the job. > There's also the possibility i need to use existing functions already using monoids... > For now I think i'll be ok with ADTs and one common wrapper for all elements. > > Thanks still, I'll think about your idea, it's rather interesting. > > Le mardi 24 mai 2016, Daniel Bergey a ?crit : >> On 2016-05-23 at 12:06, Silent Leaf wrote: >>> Say there's a class, many types that can instantiate it. Then, i in fact need to be able >>> to concatenate (mappend would be ideal!), make lists of values of different types, all >>> instantiating the class. >> >> In most cases, when Haskell beginners want to make a list that contains >> several types from a single type class, there's a better way to organize >> the code. If you post your code, I'll try to suggest a specific >> solution. >> >> In general, try to find a simple data type that captures the same fields >> & functions as an unknown type that is part of the type class. Here's >> an example. >> >> We have a type class for vectors in a metric space, and instances for >> 2D, 3D, etc. >> >>> class Metric v where >>> length :: v -> Double >>> (*^) :: Double -> v -> v >> >> This class has the law: s * length v == length (s *^ v) >> >> Instead of a heterogeneous list [ V2 1 2, V3 3 4 5, V4 6 7 8 9], we make >> a list that just has the length of each vector, and lets us multiply >> those lengths by a scalar. In this case, we don't even need to write a >> new data type, the type is simply Double. We can write: >> >>> [ length (V2 1 2), length (V3 3 4 5), length (V4 6 7 8 9) ] >> >> And (*) gives us what Metric does with (*^). Of course, with your >> class, it's probably not so obvious how to transform the class this way. >> >> It's certainly possible to make a record with functions as members, >> moving in the object-oriented direction. Existential types (with a >> class constraint inside the data constructor) are even more rarely used. >> >> cheers, >> bergey >> > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From code at funwithsoftware.org Sat May 28 06:53:56 2016 From: code at funwithsoftware.org (Patrick Pelletier) Date: Fri, 27 May 2016 23:53:56 -0700 Subject: [Haskell-beginners] documenting individual method arguments with Haddock Message-ID: <57494084.7050307@funwithsoftware.org> In Haddock, individual function arguments can be documented like this: f :: Int -- ^ The 'Int' argument -> Float -- ^ The 'Float' argument -> IO () -- ^ The return value Since a typeclass method is very much like a function, I assumed I could document individual arguments of methods the same way. For example: -- | Class representing a connection to a collection of bulbs. -- In the case of a LAN connection, this would be all bulbs on the LAN. -- In the case of a cloud connection, this would be all bulbs associated -- with the cloud account for a particular access token. class Connection t where -- | Retrieve information about some or all lights. Corresponds to -- endpoint. -- Beware that on a @LanConnection@, it takes time for lights to be -- discovered, so the list of lights will be empty immediately after -- the connection is created. listLights :: t -- ^ The connection. -> [Selector] -- ^ The lights to list. -> [InfoNeeded] -- ^ A hint about what information is desired -- in the results. This hint is used -- by @LanConnection@, but is ignored by -- @CloudConnection at . -> IO [LightInfo] However, when I generate documentation (using Haddock 2.17.2, via "stack haddock"), the text "A hint about what information is desired" doesn't appear anywhere in the generated documentation. Is there a way I can include this sort of per-argument documentation for my typeclass methods? Thanks, --Patrick From silent.leaf0 at gmail.com Tue May 31 22:18:16 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Wed, 1 Jun 2016 00:18:16 +0200 Subject: [Haskell-beginners] why is there no typeclass common to all containers? Message-ID: All in the title. I haven't used them much, but I saw Map or Vector types were forcing the user to use qualified functions unless you want nameclash with the more basic, typically list-oriented functions. So, why not have a massive, general purpose interface so the type only can separate between containers --which would allow for cross-container polymorphism, i suppose, more easily, even though it's not necessarily the most widespread need. So, do i miss something? Is there in fact a class of that kind? If so why not? Thanks in advance! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Tue May 31 22:26:57 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Wed, 1 Jun 2016 00:26:57 +0200 Subject: [Haskell-beginners] why is there no typeclass common to all containers? In-Reply-To: References: Message-ID: In fact it all comes down to trying to add partially a feature absent from the Haskell language, which is the ability to distinguish values both on name *and* on type --thus allowing two variables of the same name if they have different types. Honestly i don't see the drawback of that name system, but i guess there must be one otherwise it'd have been chosen by default instead of the typeblind current name system. Le mercredi 1 juin 2016, Silent Leaf a ?crit : > All in the title. I haven't used them much, but I saw Map or Vector types were forcing the user to use qualified functions unless you want nameclash with the more basic, typically list-oriented functions. > So, why not have a massive, general purpose interface so the type only can separate between containers --which would allow for cross-container polymorphism, i suppose, more easily, even though it's not necessarily the most widespread need. > So, do i miss something? Is there in fact a class of that kind? If so why not? > Thanks in advance! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffbrown.the at gmail.com Tue May 31 22:57:04 2016 From: jeffbrown.the at gmail.com (Jeffrey Brown) Date: Tue, 31 May 2016 15:57:04 -0700 Subject: [Haskell-beginners] why is there no typeclass common to all containers? In-Reply-To: References: Message-ID: In Haskell typeclasses are based on what you want to do with something. If, for instance, you want to be able to map over a container, you can make it an instance of class Functor -- which all the standard containers (List, Map, Set, Tree, Maybe ...) already are. On Tue, May 31, 2016 at 3:26 PM, Silent Leaf wrote: > In fact it all comes down to trying to add partially a feature absent from > the Haskell language, which is the ability to distinguish values both on > name *and* on type --thus allowing two variables of the same name if they > have different types. > Honestly i don't see the drawback of that name system, but i guess there > must be one otherwise it'd have been chosen by default instead of the > typeblind current name system. > > > Le mercredi 1 juin 2016, Silent Leaf a ?crit : > > All in the title. I haven't used them much, but I saw Map or Vector > types were forcing the user to use qualified functions unless you want > nameclash with the more basic, typically list-oriented functions. > > So, why not have a massive, general purpose interface so the type only > can separate between containers --which would allow for cross-container > polymorphism, i suppose, more easily, even though it's not necessarily the > most widespread need. > > So, do i miss something? Is there in fact a class of that kind? If so > why not? > > Thanks in advance! :) > > _______________________________________________ > Beginners mailing list > Beginners at haskell.org > http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners > > -- Jeffrey Benjamin Brown -------------- next part -------------- An HTML attachment was scrubbed... URL: From silent.leaf0 at gmail.com Tue May 31 23:39:23 2016 From: silent.leaf0 at gmail.com (Silent Leaf) Date: Wed, 1 Jun 2016 01:39:23 +0200 Subject: [Haskell-beginners] why is there no typeclass common to all containers? In-Reply-To: References: Message-ID: sure i know that, but what about sorting, or getting an element through a certain way (i bet there's a way to isolate the way the getting is done)? deleting one, etc. those are common operations but each function for each type requires its special name and namespace because each type needs its own functions because there's to my knowledge no typeclass for typically container oriented overlodable and -loaded functions (OTHER than the functor-app-monad triad and any other typeclass already existing), that is, any other container-related function that has several equivalents across types, and that isn't already in any typeclass. i thought it was implicitly obvious in my question. in fact, way beyond the limited scope of container, i wonder why function overloading isn't chosen every time there's a common operation across types (and i mean every time). that is, as you said, every time we want to do something similar but for different types, differently. Le mercredi 1 juin 2016, Jeffrey Brown a ?crit : > In Haskell typeclasses are based on what you want to do with something. If, for instance, you want to be able to map over a container, you can make it an instance of class Functor -- which all the standard containers (List, Map, Set, Tree, Maybe ...) already are. > On Tue, May 31, 2016 at 3:26 PM, Silent Leaf wrote: >> >> In fact it all comes down to trying to add partially a feature absent from the Haskell language, which is the ability to distinguish values both on name *and* on type --thus allowing two variables of the same name if they have different types. >> Honestly i don't see the drawback of that name system, but i guess there must be one otherwise it'd have been chosen by default instead of the typeblind current name system. >> >> Le mercredi 1 juin 2016, Silent Leaf a ?crit : >> > All in the title. I haven't used them much, but I saw Map or Vector types were forcing the user to use qualified functions unless you want nameclash with the more basic, typically list-oriented functions. >> > So, why not have a massive, general purpose interface so the type only can separate between containers --which would allow for cross-container polymorphism, i suppose, more easily, even though it's not necessarily the most widespread need. >> > So, do i miss something? Is there in fact a class of that kind? If so why not? >> > Thanks in advance! :) >> _______________________________________________ >> Beginners mailing list >> Beginners at haskell.org >> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners >> > > > > -- > Jeffrey Benjamin Brown -------------- next part -------------- An HTML attachment was scrubbed... URL: