Jean Lopes | 28 Jan 00:29 2015
Picon

Project Euler #01 on HackerRank, Performance issue‏

Hello everyone! I'm learning Haskell by solving simple exercises on www.hackerrank.com...



as stated in this section: https://www.hackerrank.com/environment
constraints
version: haskell-plataform 2013.2.0.0
time limit: 5 seconds
memory: 512mb

I keep getting "timed out" on some test cases (#2 and #3). Trying to process 10^5 numbers between 1 to 10^9 seems impossible to me (Please, prove me wrong!)

here is my code: 
import Data.Maybe
import qualified Data.ByteString.Char8 as B

nearestMultipleOf :: Integral a => a -> a -> a
nearestMultipleOf n k = if mod n k == 0 then n else nearestMultipleOf (n-1) k

sumMultiplesOf :: Integral a => a -> a -> a
sumMultiplesOf n k = foldl (+) 0 [k,k*2..nearest]
    where nearest = nearestMultipleOf n k
    
solution :: Integral a => a -> a
solution n = s03 + s05 - s15
    where s03 = sumMultiplesOf (n-1) 3
          s05 = sumMultiplesOf (n-1) 5
          s15 = sumMultiplesOf (n-1) 15
 
main = do
    c <- B.getContents
    let ns = tail $ B.lines c
    putStr $ unlines $ map show $ map (solution . fst . fromJust . B.readInt) ns

as always, any input is really welcome!
<div><div dir="ltr">
<div><span>Hello everyone! I'm learning Haskell by solving simple exercises on www.hackerrank.com...</span></div>
<div><span><br></span></div>
<div><span><br></span></div>
<div><span>The problem to be solved: <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler001">https://www.hackerrank.com/contests/projecteuler/challenges/euler001</a></span></div>
<div><span><br></span></div>
<div><span>as stated in this section: <a href="https://www.hackerrank.com/environment">https://www.hackerrank.com/environment</a></span></div>
<div><span>constraints</span></div>
<div><span>version: haskell-plataform 2013.2.0.0</span></div>
<div><span>time limit: 5 seconds</span></div>
<div><span>memory: 512mb</span></div>
<div><span><br></span></div>
<div><span>I keep getting "timed out" on some test cases (#2 and #3). Trying to process 10^5 numbers between 1 to 10^9 seems impossible to me (Please, prove me wrong!)</span></div>
<div><br></div>
<div>here is my code:&nbsp;</div>
<div>
<div>import Data.Maybe</div>
<div>import qualified Data.ByteString.Char8 as B</div>
<div><br></div>
<div>nearestMultipleOf :: Integral a =&gt; a -&gt; a -&gt; a</div>
<div>nearestMultipleOf n k = if mod n k == 0 then n else nearestMultipleOf (n-1) k</div>
<div><br></div>
<div>sumMultiplesOf :: Integral a =&gt; a -&gt; a -&gt; a</div>
<div>sumMultiplesOf n k = foldl (+) 0 [k,k*2..nearest]</div>
<div>&nbsp; &nbsp; where nearest = nearestMultipleOf n k</div>
<div>&nbsp; &nbsp;&nbsp;</div>
<div>solution :: Integral a =&gt; a -&gt; a</div>
<div>solution n = s03 + s05 - s15</div>
<div>&nbsp; &nbsp; where s03 = sumMultiplesOf (n-1) 3</div>
<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s05 = sumMultiplesOf (n-1) 5</div>
<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s15 = sumMultiplesOf (n-1) 15</div>
<div><span>&nbsp;</span></div>
<div>main = do</div>
<div>&nbsp; &nbsp; c &lt;- B.getContents</div>
<div>&nbsp; &nbsp; let ns = tail $ B.lines c</div>
<div>&nbsp; &nbsp; putStr $ unlines $ map show $ map (solution . fst . fromJust . B.readInt) ns</div>
</div>
<div><br></div>
<div>as always, any input is really welcome!</div>
</div></div>
Michal Kawalec | 27 Jan 15:45 2015

GPIO/I2C/PWM and Haskell

Hey list,

I got myself a Beaglebone and will use it to stabilize and fly a drone
with Haskell. The ghc support seems good enough (text doesn't compile,
everything else does), but I have a question about inputs/outputs.

They are all set through sysfs, and I think a wrapper over it would be
easiest and most straightforward to have. The operation of most pins
goes along the lines of 'activate a pin -> do some stuff -> turn it
off'. Is there some particular mechanism/library you would suggest me to
look into to handle that? Any thoughts or own experience with doing
similar things with Haskell?

Any tips will be appreciated:)
Michal

Hey list,

I got myself a Beaglebone and will use it to stabilize and fly a drone
with Haskell. The ghc support seems good enough (text doesn't compile,
everything else does), but I have a question about inputs/outputs.

They are all set through sysfs, and I think a wrapper over it would be
easiest and most straightforward to have. The operation of most pins
goes along the lines of 'activate a pin -> do some stuff -> turn it
off'. Is there some particular mechanism/library you would suggest me to
look into to handle that? Any thoughts or own experience with doing
similar things with Haskell?

Any tips will be appreciated:)
Michal

Animesh Saxena | 27 Jan 05:43 2015

Fixed Point function

I stumbled across this example as a shiny way of explaining why Lazy eval matters....

    fact = fix $ \f n -> if n == 0 then 1 else n * f (n-1)
fix f = f (fix f)

With lazy eval, I get 

fact 4 = fix $ \f 4 (......)
since haskell goes outside to inside I have,

fac 4 = $ \f 4 (......) (fix $ \f 4 (......))
Now the first chunk can get evaluated, but what about the rest of the expression. The outer "f" from "fix f" function has the parameter (fix f). So when writing "f (fix f)" apparently f got evaluated without using this parameter. I understand that the anonymous lambda does have 4 as the param, but some how "f (fix f)" doesn't feel complete. 

-Animesh


<div>
<div>I stumbled across this example as a shiny way of explaining why Lazy eval matters....</div>
<div><br></div>
<div><div>&nbsp; &nbsp; fact = fix $ \f n -&gt; if n == 0 then 1 else n * f (n-1)</div></div>
<div>fix f = f (fix f)</div>
<div><br></div>
<div>With lazy eval, I get&nbsp;</div>
<div><br></div>
<div>fact 4 = fix $ \f 4 (......)</div>
<div>since haskell goes outside to inside I have,</div>
<div><br></div>
<div>fac 4 =&nbsp;$ \f 4 (......)&nbsp;(fix&nbsp;$ \f 4 (......))</div>
<div>Now the first chunk can get evaluated, but what about the rest of the expression. The outer "f" from "fix f" function has the parameter (fix f). So when writing "f (fix f)" apparently f got evaluated without using this parameter. I understand that the anonymous lambda does have 4 as the param, but some
 how "f (fix f)" doesn't feel complete.&nbsp;</div>
<div><br></div>
<div>-Animesh</div>
<div><br></div>
<div><br></div>
</div>
Hans Georg Schaathun | 26 Jan 13:19 2015
Picon

Avoiding stack space overflow

Hi,

can someone give some hints on how to get around a stack space
overflow?

My problem is with the training function for a neural network:

trainNetwork :: Double -> Samples -> Int -> Network -> Network
trainNetwork _ _ 0 n = n
trainNetwork eta samples c n = trainNetwork eta samples (c-1) $!
                             epoch eta n samples
epoch :: Double -> Network -> Samples -> Network

So trainNetwork runs epoch c times, each time taking a Network
in and modifying the Network as output.  Clearly, space complexity
can be made constant in c, but I get stack overflow if and only
if c is too large.

As you can see, I have tried to make the epoch evaluation strict
($!).  I have also tried bang patterns on the input parameter n,
and I have tried rewriting with foldr/foldl/foldl', and I have
tried switchin the inner and outer calls (epoch vs. trainNetwork),
all to no avail.

I reckon this loop like pattern should be fairly common ... 
does it have a common solution too?

TIA
--

-- 
:-- Hans Georg
Alexis Praga | 24 Jan 18:29 2015

Help in reading XML into a data type with HXT

Hi,

I am trying to read a very simple xml node containing a list of other xml nodes into a data structure. Running
the code yields :

    fatal error: document unpickling failed
    xpCheckEmptyContents: unprocessed XML content detected
    context:    element "animelist"
    contents:
      <title>Bleach</title>
      <title>Naruto</title>

Can you help me debug this ? The code and xml are below :

8<---Code---------------------------------------------------------------------

module Main where

import System.Environment
import Text.XML.HXT.Core

type Anime = String
type AnimeList = [Anime]

xpAnime :: PU Anime
xpAnime 
  = xpElem "title" $ xpText

xpAnimeList :: PU AnimeList
xpAnimeList 
  = xpElem "animelist" $ xpList $ xpAnime 

main :: IO ()
main = do
  [src] <- getArgs
  a <- runX  ( xunpickleDocument xpAnimeList [] src)
  mapM_ putStrLn a
  return ()
8<----------------------------------------------------------------------------

8<---XML---------------------------------------------------------------------
<animelist> 
  <title>Bleach</title>
  <title>Naruto</title>
</animelist>
8<----------------------------------------------------------------------------

Thanks,

-- 
Alexis Praga, PhD Student (CERFACS)
GPG key : AD4A AF6D BB5C 042F 9422  1223 06E1 C1BF E287 65D0
Hi,

I am trying to read a very simple xml node containing a list of other xml nodes into a data structure. Running
the code yields :

    fatal error: document unpickling failed
    xpCheckEmptyContents: unprocessed XML content detected
    context:    element "animelist"
    contents:
      <title>Bleach</title>
      <title>Naruto</title>

Can you help me debug this ? The code and xml are below :

8<---Code---------------------------------------------------------------------

module Main where

import System.Environment
import Text.XML.HXT.Core

type Anime = String
type AnimeList = [Anime]

xpAnime :: PU Anime
xpAnime 
  = xpElem "title" $ xpText

xpAnimeList :: PU AnimeList
xpAnimeList 
  = xpElem "animelist" $ xpList $ xpAnime 

main :: IO ()
main = do
  [src] <- getArgs
  a <- runX  ( xunpickleDocument xpAnimeList [] src)
  mapM_ putStrLn a
  return ()
8<----------------------------------------------------------------------------

8<---XML---------------------------------------------------------------------
<animelist> 
  <title>Bleach</title>
  <title>Naruto</title>
</animelist>
8<----------------------------------------------------------------------------

Thanks,

--

-- 
Alexis Praga, PhD Student (CERFACS)
GPG key : AD4A AF6D BB5C 042F 9422  1223 06E1 C1BF E287 65D0
Robert Dodier | 24 Jan 06:02 2015
Picon

ghc failed to compile trifecta while installing idris

Hi, 

I'm trying to install Idris. 

I am working on Ubuntu 14.04. ghc --version reports 7.6.3.

After installing Haskell via apt-get, I then executed cabal update,
which succeeded.

I then tried cabal install idris and it eventually failed while
trying to install trifecta.

I then tried cabal install -v3 idris and got the following info
about the trifecta problem, which I've appended to this message
as a PS.

Maybe I can patch Highlight.hs? How would I go about that?
Unpack the tar.gz, patch the file, and repack it?

For the record, I tried to follow the instructions at:
https://github.com/idris-lang/Idris-dev/wiki/Idris-on-Ubuntu
but ran into various errors, e.g., cabal install cabal-install
failed with ExitFailure 139. 

Thanks for any advice.

best,

Robert Dodier

PS. The tail end of the output of cabal install -v3 idris:

[ 8 of 13] Compiling Text.Trifecta.Highlight (
src/Text/Trifecta/Highlight.hs, dist/build/Text/Trifecta/Highlight.o )
*** Parser:
*** Renamer/typechecker:

src/Text/Trifecta/Highlight.hs:46:15:
    Ambiguous occurrence `Comment'
    It could refer to either `Text.Blaze.Internal.Comment',
                             imported from `Text.Blaze.Internal' at
src/Text/Trifecta/Highlight.hs:35:1-26
                          or `Text.Parser.Token.Highlight.Comment',
                             imported from `Text.Parser.Token.Highlight' at
src/Text/Trifecta/Highlight.hs:36:1-34
Upsweep partially successful.
*** Deleting temp files:
Deleting: /tmp/ghc13030_0/ghc13030_0.s
Warning: deleting non-existent /tmp/ghc13030_0/ghc13030_0.s
link(batch): upsweep (partially) failed OR
   Main.main not exported; not linking.
*** Deleting temp files:
Deleting: /tmp/ghc13030_0/ghc13030_0.hscpp
*** Deleting temp dirs:
Deleting: /tmp/ghc13030_0
/usr/bin/ghc returned ExitFailure 1
Failed to install trifecta-1.5
World file is already up to date.
cabal: Error: some packages failed to install:
idris-0.9.16 depends on trifecta-1.5 which failed to install.
trifecta-1.5 failed during the building phase. The exception was:
ExitFailure 1

Animesh Saxena | 24 Jan 02:21 2015

Show and showList

I am trying to understand the concept of overlapping instances. In the book "Real World Haskell" there is an example of showList which avoids overlapping instances. 

As per my understanding showList is taking the same problem that method "show" would have for overlapping instances. Here's the snippet which explains how it works...

"The Show class defines both a show method, which renders one value, and a showList method, which renders a list of values. The default implementation of showList renders a list using square brackets and commas.

The instance of Show for [a] is implemented using showList. The instance of Show for Char provides a special implementation of showList that uses double quotes and escapes non-ASCII-printable characters.

As a result, if someone applies show to a [Char] value, the implementation of showList will be chosen, and it will correctly render the string using quotes.


At least sometimes, then, we can avoid the need for the OverlappingInstances extension with a little bit of lateral thinking." 


GHC Code

class Show a where

  showsPrec :: Int -> a -> ShowS

  show :: a -> String

  showList :: [a] -> ShowS


*Main> show [1,2,3]

"[1,2,3]"

*Main> show ['a','b','c']

"\"abc\""

*Main>

It's the same problem now transfered to showList which will be declared differently for a list of int's or a list of chars, but still it outputs them differently as can be seen from the above code. How it is able to differentiate without throwing up the overlap error?


-A





<div>
<div>I am trying to understand the concept of overlapping instances. In the book "Real World Haskell" there is an example of showList which avoids overlapping instances.&nbsp;</div>
<div><br></div>
<div>As per my understanding showList is taking the same problem that method "show" would have for overlapping instances. Here's the snippet which explains how it works...</div>
<div><br></div>
<div>"<span>The </span><span>Show </span><span>class defines both a </span><span>show </span><span>method, which renders one value, and a </span><span>showList
</span><span>method, which renders a list of values. The default implementation of </span><span>showList </span><span>renders
a list using square brackets and commas.</span>
</div>
<div><span><br></span></div>
		
	
	
		<div class="page" title="Page 195">
			<div class="layoutArea">
				<div class="column">
					
					<p><span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">The instance of </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">Show </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">for </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">[a] </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">is implemented using </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">showList</span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">. The instance of </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">Show </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">for
</span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">Char </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">provides a special implementation of </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">showList </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">that uses double quotes and escapes
non-ASCII-printable characters.
</span></span></p>
					<p><span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">As a result, if someone applies </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">show </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">to a </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">[Char] </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">value, the implementation of
</span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">showList </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">will be chosen, and it will correctly render the string using quotes.
</span></span></p>
<p><span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';"><br></span></span></p>
					<p><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">At least sometimes, then, we can avoid the need for the </span><span data-mce-style="font-size: 9.000000pt; font-family: 'TheSansMonoCd';">OverlappingInstances </span><span data-mce-style="font-size: 10.000000pt; font-family: 'font000000001a5a194d';">extension
with a little bit of lateral thinking."&nbsp;</span></p>
<p><span><br></span></p>
<p><span><span data-mce-style="font-size: 13px; line-height: 20px;">GHC Code</span></span></p>
<p><span><span data-mce-style="font-size: 13px; line-height: 20px;">class Show a where</span></span></p>
<p><span><span data-mce-style="font-size: 13px; line-height: 20px;">&nbsp; showsPrec :: Int -&gt; a -&gt; ShowS</span></span></p>
<p><span>&nbsp; show :: a -&gt; String</span></p>
<p></p>
<p><span>&nbsp; showList :: [a] -&gt; ShowS</span></p>
<p><span><br></span></p>
<p><span>*Main&gt; show [1,2,3]</span></p>
<p><span>"[1,2,3]"</span></p>
<p><span>*Main&gt; show ['a','b','c']</span></p>
<p><span>"\"abc\""</span></p>
<p><span>*Main&gt;</span></p>
<p><span>It's the same problem now transfered to showList which will be declared differently for a list of int's or a list of chars, but still it outputs them differently as can be seen from the above code.&nbsp;</span><span>How it is able to differentiate without throwing up the overlap error?</span></p>
<p><span><br></span></p>
<p><span>-A</span></p>
<p><span><br></span></p>
<p><span><br></span></p>
<p><span><br></span></p>
<p><span><br></span></p>
				</div>
			</div>
		</div>
</div>
Sylvain Henry | 23 Jan 19:50 2015
Picon

Re: help with IO guards

Hi,

Using LambdaCase extension, you can write something quite elegant:

{-# LANGUAGE LambdaCase #-}

f :: Int -> IO String
f x = getDBRecord x >>= \case
    dbOutput
        | null dbOutput -> return "no db record"
        | otherwise      -> return "we got some db records"

Or better:

f :: Int -> IO String
f x = getDBRecord x >>= \case
          [] -> return "no db record"
          _  -> return "we got some db records"

But you can also use another function for the pure part:

recordMsg :: [a] -> String
recordMsg [] = "no db record"
recordMsg _ = "we got some db records"

f :: Int -> IO String
f = fmap recordMsg . getDBRecord

Regards,
Sylvain


2015-01-15 12:51 GMT+01:00 Miro Karpis <miroslav.karpis <at> gmail.com>:
Hi,

please is there a way to have guards with 'where' that communicates with IO? Or is there some other more elegant way? I can do this with classic if/else,...but I just find it nicer with guards.


I have something like this (just an example):


f :: Int -> IO String
f x
    | null dbOutput = return "no db record"
    | otherwise = return "we got some db records"
    where dbOutput = getDBRecord x


getDBRecord :: Int -> IO [Int]
getDBRecord recordId = do
    putStrLn $ "checking dbRecord" ++ show recordId
    --getting data from DB
    return [1,2]


problem is that db dbOutput is IO and the guard check does not like it:
 
Couldn't match expected type ‘[a0]’ with actual type ‘IO [Int]’
    In the first argument of ‘null’, namely ‘dbOutput’
    In the expression: null dbOutput



Cheers,
Miro

_______________________________________________
Beginners mailing list
Beginners <at> haskell.org
http://www.haskell.org/mailman/listinfo/beginners


<div><div dir="ltr">Hi,<br><br>Using LambdaCase extension, you can write something quite elegant:<br><br>{-# LANGUAGE LambdaCase #-}<br><br>f :: Int -&gt; IO String<br>f x = getDBRecord x &gt;&gt;= \case<br>&nbsp;&nbsp;&nbsp; dbOutput <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | null dbOutput -&gt; return "no db record"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | otherwise&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -&gt; return "we got some db records"<br><br>Or better:<br><br>f :: Int -&gt; IO String<br>f x = getDBRecord x &gt;&gt;= \case<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [] -&gt; return "no db record"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _&nbsp; -&gt; return "we got some db records"<br><br>But you can also use another function for the pure part:<br><br>recordMsg :: [a] -&gt; String<br>recordMsg [] = "no db record"<br>recordMsg _ = "we got some db records"<br><br>f :: Int -&gt; IO String<br>f = fmap recordMsg . getDBRecord<br><br>Regards,<br>Sylvain<br><br><div class="gmail_extra">
<br><div class="gmail_quote">2015-01-15 12:51 GMT+01:00 Miro Karpis <span dir="ltr">&lt;<a href="mailto:miroslav.karpis <at> gmail.com" target="_blank">miroslav.karpis <at> gmail.com</a>&gt;</span>:<br><blockquote class="gmail_quote">
<div dir="ltr">
<div>
<div>
<div>
<div>Hi,<br><br>
</div>please is there a way to have guards with 'where' that communicates with IO? Or is there some other more elegant way? I can do this with classic if/else,...but I just find it nicer with guards.<br><br><br>
</div>I have something like this (just an example):<br><br><br>f :: Int -&gt; IO String<br>f x<br>&nbsp;&nbsp;&nbsp; | null dbOutput = return "no db record"<br>&nbsp;&nbsp;&nbsp; | otherwise = return "we got some db records"<br>&nbsp;&nbsp;&nbsp; where dbOutput = getDBRecord x<br><br><br>getDBRecord :: Int -&gt; IO [Int]<br>getDBRecord recordId = do<br>&nbsp;&nbsp;&nbsp; putStrLn $ "checking dbRecord" ++ show recordId<br>&nbsp;&nbsp;&nbsp; --getting data from DB<br>&nbsp;&nbsp;&nbsp; return [1,2]<br><br><br>
</div>
<div>problem is that db dbOutput is IO and the guard check does not like it:<br>&nbsp; <br>Couldn't match expected type &lsquo;[a0]&rsquo; with actual type &lsquo;IO [Int]&rsquo;<br>&nbsp;&nbsp;&nbsp; In the first argument of &lsquo;null&rsquo;, namely &lsquo;dbOutput&rsquo;<br>&nbsp;&nbsp;&nbsp; In the expression: null dbOutput<br><br><br>
</div>
<div><br></div>Cheers,<br>
</div>Miro<br>
</div>
<br>_______________________________________________<br>
Beginners mailing list<br><a href="mailto:Beginners <at> haskell.org">Beginners <at> haskell.org</a><br><a href="http://www.haskell.org/mailman/listinfo/beginners" target="_blank">http://www.haskell.org/mailman/listinfo/beginners</a><br><br>
</blockquote>
</div>
<br>
</div>
</div></div>
Jeffrey Brown | 22 Jan 01:23 2015
Picon

Defining an instance: Syntax that works exactly sometimes

Dear Haskellers,

The following compiles. (Rev stands for Reversible, and Dirn for Direction.)

    class Rev a where
        rev :: a -> a
   
    data Dirn = Succ | Pred
        deriving (Eq, Show, Ord)

    -- implement Ord
    (<=) Succ Pred = False
    (<=) _ _ = True
   
    -- implement Rev
    instance Rev Dirn where
        rev Succ = Pred
        rev Pred = Succ

But if I try to define the Rev instance the same way the Ord instance is being defined, it does not compile:

    class Rev a where
        rev :: a -> a
   
    data Dirn = Succ | Pred
        deriving (Eq, Show, Ord, Rev)
   
    -- implement Ord, because Dirn is used as a key in a Map
    (<=) Succ Pred = False
    (<=) _ _ = True
   
    -- implement Rev
    rev Succ = Pred
    rev Pred = Succ

What's going on?

Many thanks,
Jeff

<div><div dir="ltr">Dear Haskellers,<br><br>The following compiles. (Rev stands for Reversible, and Dirn for Direction.)<br><br>&nbsp;&nbsp;&nbsp; class Rev a where<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rev :: a -&gt; a<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; data Dirn = Succ | Pred<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; deriving (Eq, Show, Ord)<br><br>&nbsp;&nbsp;&nbsp; -- implement Ord<br>&nbsp;&nbsp;&nbsp; (&lt;=) Succ Pred = False<br>&nbsp;&nbsp;&nbsp; (&lt;=) _ _ = True<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; -- implement Rev<br>&nbsp;&nbsp;&nbsp; instance Rev Dirn where<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rev Succ = Pred<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rev Pred = Succ<br><br>But if I try to define the Rev instance the same way the Ord instance is being defined, it does not compile:<br><br>&nbsp;&nbsp;&nbsp; class Rev a where<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rev :: a -&gt; a<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; data Dirn = Succ | Pred<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; deriving (Eq, Show, Ord, Rev)<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; -- implement Ord, because Dirn is used as a key in a Map<br>&nbsp;&nbsp;&nbsp; (&lt;=) Succ Pred = False<br>&nbsp;&nbsp;&nbsp; (&lt;=) _ _ = True<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; -- implement Rev<br>&nbsp;&nbsp;&nbsp; rev Succ = Pred<br>&nbsp;&nbsp;&nbsp; rev Pred = Succ<br><br>What's going on?<br><br>Many thanks,<br>Jeff<br><br>
</div></div>
Elias Diem | 19 Jan 15:29 2015
Picon

Let the compiler do the work

Hi there

I'm referring to a post from Stefan Höck and will quote from 
there:

http://article.gmane.org/gmane.comp.lang.haskell.beginners/14198

<quote>
Now, load this into GHCi or compile with GHC. If it compiles, you're
on the right track. Now, you want to implement it using a fold
(try both, foldl and foldr):

  last5 :: [a] -> Maybe a
  last5 xs = foldr _ _ xs

The underscores are 'type holes'. This tells the compiler to give you
some information about what is supposed to be placed at the two
positions. For the moment, we are only interested in the types of the
things that go there. The compiler will tell you, that
the hole at the first position is of type

  a -> Maybe a -> Maybe a
</quote>

How does the compiler tell me this? I didn't find any flags 
for GHC to turn this on. What do I miss?

--

-- 
Greetings
Elias

_______________________________________________
Beginners mailing list
Beginners <at> haskell.org
http://www.haskell.org/mailman/listinfo/beginners
Dmitriy Matrosov | 19 Jan 14:01 2015
Picon

Defining ExtensionClass (Maybe a) instance in xmonad.

Hi.

I've tried to define (Maybe a) instance for ExtensionClass from XMonad/Core.hs
in such way, that extensionType value would use the same data constructor as
was used for the type a itself. But the code below typechecks only, if i add
(Show a) and (Read a) constraints to (Maybe a) instance definition, what makes
such definition useless for types, which do not have these instances and do
not want to use PersistentExtension .

How can i define (Maybe a) instance without (Show a) and (Read a) constraints?

> {-# LANGUAGE ExistentialQuantification #-}
> import Data.Typeable

> -- This one does not typecheck
> --instance ExtensionClass a => ExtensionClass (Maybe a) where
> instance (Show a, Read a, ExtensionClass a) => ExtensionClass (Maybe a) where
>     initialValue = Nothing
>     extensionType x = let Just i = (Just initialValue) `asTypeOf` x
>                       in  case extensionType i of
>                             PersistentExtension _ -> PersistentExtension x
>                             StateExtension _ -> StateExtension x


Here is class definition from XMonad/Core.hs:

> class Typeable a => ExtensionClass a where
>     initialValue :: a
>     extensionType :: a -> StateExtension
>     extensionType = StateExtension

> data StateExtension =
>     forall a. ExtensionClass a => StateExtension a
>   | forall a. (Read a, Show a, ExtensionClass a) => PersistentExtension a

--
    Dmitriy Matrosov
<div><div dir="ltr">Hi.<br><br>I've tried to define (Maybe a) instance for ExtensionClass from XMonad/Core.hs<br>in such way, that extensionType value would use the same data constructor as<br>was used for the type a itself. But the code below typechecks only, if i add<br>(Show a) and (Read a) constraints to (Maybe a) instance definition, what makes<br>such definition useless for types, which do not have these instances and do<br>not want to use PersistentExtension .<br><br>How can i define (Maybe a) instance without (Show a) and (Read a) constraints?<br><br>&gt; {-# LANGUAGE ExistentialQuantification #-}<br>&gt; import Data.Typeable<br><br>&gt; -- This one does not typecheck<br>&gt; --instance ExtensionClass a =&gt; ExtensionClass (Maybe a) where<br>&gt; instance (Show a, Read a, ExtensionClass a) =&gt; ExtensionClass (Maybe a) where<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; initialValue = Nothing<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; extensionType x = let Just i = (Just initialValue) `asTypeOf` x<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; in&nbsp; case extensionType i of<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PersistentExtension _ -&gt; PersistentExtension x<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; StateExtension _ -&gt; StateExtension x<br><br><br>Here is class definition from XMonad/Core.hs:<br><br>&gt; class Typeable a =&gt; ExtensionClass a where<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; initialValue :: a<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; extensionType :: a -&gt; StateExtension<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; extensionType = StateExtension<br><br>&gt; data StateExtension =<br>&gt;&nbsp;&nbsp;&nbsp;&nbsp; forall a. ExtensionClass a =&gt; StateExtension a<br>&gt;&nbsp;&nbsp; | forall a. (Read a, Show a, ExtensionClass a) =&gt; PersistentExtension a<br><br>--<br>&nbsp;&nbsp;&nbsp; Dmitriy Matrosov<br>
</div></div>

Gmane