Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Magnus Therning
AFAIK there is no way to do that, thouhg scion[1] may offer it.

Personally I develop more complex local functions at the top-level,
and once I'm happy with it I perform some re-factoring and move it in.

/M

[1]: https://github.com/nominolo/scion/blob/master/README.markdown


-- 
Magnus Therning                      OpenPGP: 0xAB4DFBA4
email: mag...@therning.org   jabber: mag...@therning.org
twitter: magthe               http://therning.org/magnus

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Testing Implementation vs Model - Records or Type Classes?

2011-04-08 Thread Heinrich Apfelmus

Hello,

I'm writing a small Haskell library for functional reactive programming. 
The core of the library consists of two data types and several 
primitives. However, I have programmed this core *twice*: once as a 
*model* that displays the intended semantics, and once as the actual 
*implementation* to be used in production code.


Of course, I would like to use QuickCheck to test that the 
implementation gives the same results as the model. My problem is: how 
to organize this with the minimum amount of boilerplate?


It appears that I can use *multiparameter type classes* to solve this, 
but I'm not sure I'm happy with this, in particular because it makes the 
generated Haddock less readable (see 3) below). On the other hand, I 
could also use *record wildcards* to conveniently reify a module into a 
record data structure. But that will give me problems with combinators 
that are derived from the core combinators (see 2) below).


Haskell Café, what are your suggestions and ideas?


In particular, I wish to:

1) Write examples to be QuickChecked only once.
I imagine that my main function for testing looks like this

test_equal example =
  forAll $ \input - example model input
  == example implementation input

where  example  an expression involving the combinators from my library. 
The point is that I don't want to write  example  twice, once for each 
version.


2) Use derived combinators.
For reference, here the full signature of the core combinators:

   data Event a
   data Behavior a

   instance Functor Behavior
   instance Applicative Behavior
   instance Functor Event
   instance Monoid  (Event a)

   filter :: (a - Bool) - Event a - Event a
   apply  :: Behavior (a - b) - Event a - Event b
   accumB :: a - Event (a - a) - Behavior a

When writing tests, I also want to use common derived combinators, like, say

   filterJust :: Event (Maybe a) - Event a
   filterJust = fmap fromJust . filter isJust

without implementing them twice.

3) Obtain readable Haddock.
I like the simplicity and readability of an ordinary module signature. 
In contrast, libraries with many type class scare me. Or is there a way 
to make this less scary?


I'm not sure about the last one:
4) Make both model and implementation available to the user,
so that he can QuickCheck his own programs as well. Since the 
implementation makes heavy use of IO, it is a bit harder to test 
automatically, so the model might be useful to have.



Best regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Parsing HTML tables with HXT

2011-04-08 Thread Dmitry Simonchik
Dear Cafe,

Can someone please help me with getting the value of the table cell with HXT
in the following html:

table class=tblc
tr
  td class=tdcx/td
  tdy/td
/tr
tr
  td class=tdca/td
  tdb/td
/tr
/table

I need the value of the second cell in a row that has first cell with some
predefined value (in the example above it can be x or a) I need the arrow of
the type (IOSArrow XmlTree String) How to write it?

Thanks
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] FFI for a beginner

2011-04-08 Thread Andrew Pennebaker
ncurses is proving too difficult to setup, so I'm working on a new library
called charm. The C code works by itself, but I can't compile a Haskell
wrapper for it. While the tutorials at
HaskellWikihttp://www.haskell.org/haskellwiki/FFI_complete_examplesare
helpful, they're outdated. Argh! The
docshttp://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html#glasgow-foreign-headerssay
that -#include pragmas no longer work, but fail to explain how to load
code without them. Suffice to say I have no recourse but trial and error.

GitHub: charm https://github.com/mcandre/charm and
hscharmhttps://github.com/mcandre/hscharm

https://github.com/mcandre/charm$ make
cp /usr/include/charm.c .
ghc --make -fforce-recomp -o hellocharm hellocharm.hs charm.hs charm.c
-I/usr/include -dylib-install-name /usr/lib/libcharm.dynlib
[1 of 2] Compiling Charm( charm.hs, charm.o )
[2 of 2] Compiling Main ( hellocharm.hs, hellocharm.o )
Linking hellocharm ...
ld: duplicate symbol _Charm_getWidth_info in charm.o and charm.o
collect2: ld returned 1 exit status
make: *** [hellocharm] Error 1

Cheers,

Andrew Pennebaker
www.yellosoft.us
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] fmap and LaTeX

2011-04-08 Thread Mitar
Hi!

Is there for $ (fmap) operator some nice looking symbol in mathematics, LaTeX?

I am looking here:

http://www.soi.city.ac.uk/~ross/papers/Applicative.html
http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base/Control-Applicative.html

but only for other operators there are nice symbols, and $ is left as it is.

I have also tried \mathbin{\$} but it adds space around $ (at least
in lhs2tex), so it looks ugly.


Mitar

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] fmap and LaTeX

2011-04-08 Thread Daniel Fischer
On Friday 08 April 2011 14:05:46, Mitar wrote:
 
 I have also tried \mathbin{\$} but it adds space around $ (at least
 in lhs2tex), so it looks ugly.

Would \mathbin{\langle\$\rangle} look better?

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] fmap and LaTeX

2011-04-08 Thread Henning Thielemann
Mitar schrieb:
 Hi!
 
 Is there for $ (fmap) operator some nice looking symbol in mathematics, 
 LaTeX?
 
 I am looking here:
 
 http://www.soi.city.ac.uk/~ross/papers/Applicative.html
 http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base/Control-Applicative.html
 
 but only for other operators there are nice symbols, and $ is left as it is.
 
 I have also tried \mathbin{\$} but it adds space around $ (at least
 in lhs2tex), so it looks ugly.

Does \langle\$\rangle look better for your taste?


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Henning Thielemann
Magnus Therning schrieb:
 AFAIK there is no way to do that, thouhg scion[1] may offer it.
 
 Personally I develop more complex local functions at the top-level,
 and once I'm happy with it I perform some re-factoring and move it in.

I would not write large local functions at all. I would leave them
top-level but do not export them. This also allows to test them from GHCi.


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] fmap and LaTeX

2011-04-08 Thread Mitar
Hi!

Uuu, nice. Thanks Daniel and Henning.


Mitar

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Evan Laforge
On Fri, Apr 8, 2011 at 5:24 AM, Henning Thielemann
schlepp...@henning-thielemann.de wrote:
 Magnus Therning schrieb:
 AFAIK there is no way to do that, thouhg scion[1] may offer it.

 Personally I develop more complex local functions at the top-level,
 and once I'm happy with it I perform some re-factoring and move it in.

 I would not write large local functions at all. I would leave them
 top-level but do not export them. This also allows to test them from GHCi.

Agreed, I do this as well.  However, I occasionally would like to do a
reverse infer, for example:

bigFunction = ... helper x y z

helper = undefined

Now I want to find out what type 'helper' should be in order that it
typecheck within bigFunction.  Obviously 'undefined's type 'a'
trivially satisfies that, so it can't be the most general possible
type because that's always just 'a'.

Currently what I do is declare a signature for helper, and then if it
gets a type error try to figure out how to fix it.  It's usually not
very hard, but it would be slick to have the signature filled in
automatically.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Testing Implementation vs Model - Records or Type Classes?

2011-04-08 Thread Twan van Laarhoven

On 08/04/11 11:54, Heinrich Apfelmus wrote:

Hello,

I'm writing a small Haskell library for functional reactive programming.
The core of the library consists of two data types and several
primitives. However, I have programmed this core *twice*: once as a
*model* that displays the intended semantics, and once as the actual
*implementation* to be used in production code.

...
Haskell Café, what are your suggestions and ideas?

...
For reference, here the full signature of the core combinators:

data Event a
data Behavior a

instance Functor Behavior
instance Applicative Behavior
instance Functor Event
instance Monoid (Event a)

filter :: (a - Bool) - Event a - Event a
apply :: Behavior (a - b) - Event a - Event b
accumB :: a - Event (a - a) - Behavior a


You don't need MPTCs to generalize the filter function:

-- this class is useful beyond this FRP library,
--  you might already be able to find it on hackage somewhere
class Functor f = Filterable f where
filter :: (a - Bool) - f a - f a
-- filter p . fmap f == fmap f . filter (p . f)
-- filter (const True) == id
-- filter p . filter q == filter (\x - p x  q x)

The apply and accumB functions are harder. Is the Behavior 
implementation for the model really different from the one of the 
implementation, which seems to be {initial::a, changes::Event a}? If 
not, you could just generalize that type by making the event type a 
parameter


data GenBehavior e a = GB a (E a)

If this is not the case, then instead of MPTCs you could also try type 
families,


class ... = FRP event where
data Behavior event
apply :: Behavior event (a - b) - event a - event b
accumB :: a - event (a - a) - Behavior event a

I don't know whether this is any better than the MPTC approach, though.


Twan

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] fmap and LaTeX

2011-04-08 Thread Daniel Fischer
On Friday 08 April 2011 14:25:41, Mitar wrote:
 Hi!
 
 Uuu, nice. Thanks Daniel and Henning.
 

Alternatively, you can kill off the spaces '' and '' produce using 
\mspace,

\newcommand{\ltgt}[1]{\mathbin{\mspace{-6mu}#1\mspace{-6mu}}}
\newcommand{\fmap}{\ltgt{\$}}

The value used in \mspace can be adjusted to personal taste, perhaps you'd 
also like to raise '' and '' for that a little, since they touch the 
baseline normally.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Magnus Therning
On Fri, Apr 8, 2011 at 13:24, Henning Thielemann
schlepp...@henning-thielemann.de wrote:
 Magnus Therning schrieb:
 AFAIK there is no way to do that, thouhg scion[1] may offer it.

 Personally I develop more complex local functions at the top-level,
 and once I'm happy with it I perform some re-factoring and move it in.

 I would not write large local functions at all. I would leave them
 top-level but do not export them. This also allows to test them from GHCi.

Indeed, but complex /= large :-)

/M

-- 
Magnus Therning                      OpenPGP: 0xAB4DFBA4
email: mag...@therning.org   jabber: mag...@therning.org
twitter: magthe               http://therning.org/magnus

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread 山本和彦
 Currently what I do is declare a signature for helper, and then if it
 gets a type error try to figure out how to fix it.  It's usually not
 very hard, but it would be slick to have the signature filled in
 automatically.

Try ghc-mod on Hackage if you are an Emacs user.

If GHC can guess the signature of helper function, haskell-mode with
ghc-mod automatically hilights the function. Typing C-cC-t inserts the
guessed signature.

http://www.mew.org/~kazu/proj/ghc-mod/en/

--Kazu

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread 山本和彦
I made a mistake. Use M-t instead of C-cC-t.

 Currently what I do is declare a signature for helper, and then if it
 gets a type error try to figure out how to fix it.  It's usually not
 very hard, but it would be slick to have the signature filled in
 automatically.
 
 Try ghc-mod on Hackage if you are an Emacs user.
 
 If GHC can guess the signature of helper function, haskell-mode with
 ghc-mod automatically hilights the function. Typing C-cC-t inserts the
 guessed signature.
 
   http://www.mew.org/~kazu/proj/ghc-mod/en/
 
 --Kazu

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Lyndon Maydwell
Agda's concept of holes seems perfect for this. Does Haskell have
anything similar?

On Fri, Apr 8, 2011 at 9:50 PM, Kazu Yamamoto k...@iij.ad.jp wrote:
 I made a mistake. Use M-t instead of C-cC-t.

 Currently what I do is declare a signature for helper, and then if it
 gets a type error try to figure out how to fix it.  It's usually not
 very hard, but it would be slick to have the signature filled in
 automatically.

 Try ghc-mod on Hackage if you are an Emacs user.

 If GHC can guess the signature of helper function, haskell-mode with
 ghc-mod automatically hilights the function. Typing C-cC-t inserts the
 guessed signature.

       http://www.mew.org/~kazu/proj/ghc-mod/en/

 --Kazu

 ___
 Haskell-Cafe mailing list
 Haskell-Cafe@haskell.org
 http://www.haskell.org/mailman/listinfo/haskell-cafe


___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] erratic behavior for System.Time.diffClockTimes

2011-04-08 Thread Warren Harris
I'm trying out GHC-7.0.3-x86_64 for Mac OS X and see what seems to be a bug in 
System.Time.diffClockTimes. The TimeDiff tdPicosec field returns values that 
seem to jump around erratically: 

test = do
  startTime - System.Time.getClockTime
  endTime - System.Time.getClockTime
  let dt = diffClockTimes endTime startTime
  putStrLn $ show dt

Prelude Test test
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, 
tdPicosec = 0}
Prelude Test test
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, 
tdPicosec = 300}
Prelude Test test
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, 
tdPicosec = -332901224613832315000}
Prelude Test test
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, 
tdPicosec = 300}
Prelude Test test
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 0, 
tdPicosec = -332901224613832285100}
Prelude Test 

I can file a bug, unless I'm overlooking something here.

Warren
___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Stateful iteratees

2011-04-08 Thread Maciej Marcin Piechotka
On Thu, 2011-04-07 at 19:04 +0200, Ertugrul Soeylemez wrote:
 Hello fellow Haskellers,
 
 I'm trying to solve a very practical problem:  I need a stateful
 iteratee monad transformer.  Explicit state passing is very inconvenient
 and would destroy the elegance of my library.
 
 There are two approaches to this:
 
   1. type MyT a m = Iteratee a (StateT MyConfig m)
   2. type MyT a m = StateT MyConfig (Iteratee a m)
 
 Both work well except in two very specific corner cases:
 
   - I need to convert the transformer to 'Iteratee a m', i.e. remove the
 state layer.  This is obviously trivial with the second variant, but
 seems very difficult with the first one, if it's possible at all.
 
   - I need to use control structures of Iteratee like catchError.  This
 is obviously trivial with the first variant, but very inconvenient
 with the second, because I would need to reinvent many wheels.
 
 Does someone know a cleaner, more elegant solution?  Encapsulating the
 state in the iteratee's input type is not an option.
 
 Many thanks in advance.

The first thing that come to my mind.

runWithState :: Iteratee a (StateT s m) b - s - Iteratee a m (b, s)
runWithState i s = do
let onDone v st = return (Right (v, st))
onCont c err = return (Left (c, err))
(i', s') - runStateT (runIter i onDone onCont) s
case i' of
  Left (c, err) - icont (\str - runWithState (c str) s') err
  Right (v, st) - idone (v, s') st

I believe it is equivalent to:

runWithState :: Iteratee a (StateT s m) b - s - Iteratee a m (b, s)
runWithState i s = do
let onDone v st = do
s' - get
return (idone (v, s') st)
onCont c err = do
s' - get
return (icont (\str - runWithState (c str) s') err)
joinIM $ evalStateT (runIter i onDone onCont) s

I haven't tested but it compiles so it should work.





___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] erratic behavior for System.Time.diffClockTimes

2011-04-08 Thread Bas van Dijk
On 8 April 2011 22:48, Warren Harris warrensomeb...@gmail.com wrote:
 I'm trying out GHC-7.0.3-x86_64 for Mac OS X and see what seems to be a bug 
 in System.Time.diffClockTimes. The TimeDiff tdPicosec field returns values 
 that seem to jump around erratically

Strange. This doesn't happen on my Ubuntu x86_64:

*Main testOLD
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0,
tdSec = 0, tdPicosec = 300}
*Main testOLD
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0,
tdSec = 0, tdPicosec = 500}
*Main testOLD
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0,
tdSec = 0, tdPicosec = 500}
*Main testOLD
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0,
tdSec = 0, tdPicosec = 600}
*Main testOLD
TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0,
tdSec = 0, tdPicosec = 600}

I also tried with the new time library but that also works as expected:

import Data.Time

test = do
  startTime - getCurrentTime
  endTime   - getCurrentTime
  let dt = diffUTCTime endTime startTime
  putStrLn $ show dt

*Main test
0.06s
*Main test
0.07s
*Main test
0.06s
*Main test
0.04s
*Main test
0.07s

Bas

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] erratic behavior for System.Time.diffClockTimes

2011-04-08 Thread Antoine Latter
On Fri, Apr 8, 2011 at 3:48 PM, Warren Harris warrensomeb...@gmail.com wrote:
 I'm trying out GHC-7.0.3-x86_64 for Mac OS X and see what seems to be a bug 
 in System.Time.diffClockTimes. The TimeDiff tdPicosec field returns values 
 that seem to jump around erratically:

 test = do
  startTime - System.Time.getClockTime
  endTime - System.Time.getClockTime
  let dt = diffClockTimes endTime startTime
  putStrLn $ show dt

 Prelude Test test
 TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 
 0, tdPicosec = 0}
 Prelude Test test
 TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 
 0, tdPicosec = 300}
 Prelude Test test
 TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 
 0, tdPicosec = -332901224613832315000}
 Prelude Test test
 TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 
 0, tdPicosec = 300}
 Prelude Test test
 TimeDiff {tdYear = 0, tdMonth = 0, tdDay = 0, tdHour = 0, tdMin = 0, tdSec = 
 0, tdPicosec = -332901224613832285100}
 Prelude Test


There's already a ticket:

http://hackage.haskell.org/trac/ghc/ticket/4970

It is specific to 64bit on Mac OS. I noticed it myself a bit ago.
Please add yourself to the CC list on the ticket if its affecting you.

Antoine

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Testing Implementation vs Model - Records or Type Classes?

2011-04-08 Thread wren ng thornton

On 4/8/11 8:55 AM, Twan van Laarhoven wrote:

-- this class is useful beyond this FRP library,
-- you might already be able to find it on hackage somewhere
class Functor f = Filterable f where
filter :: (a - Bool) - f a - f a
-- filter p . fmap f == fmap f . filter (p . f)
-- filter (const True) == id
-- filter p . filter q == filter (\x - p x  q x)


There are a few other methods that should be added to this typeclass. In 
particular,


filterMap :: (a - Maybe b) - f a - f b

which fuses the first rule and saves the redundant passes and evaluations.

In a similar vein you may want a class for versions that allow 
applicative/monadic functions along with the sequenceA/sequence 
capabilities of Traversable.


--
Live well,
~wren

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread wren ng thornton

On 4/8/11 8:24 AM, Henning Thielemann wrote:

Magnus Therning schrieb:

AFAIK there is no way to do that, thouhg scion[1] may offer it.

Personally I develop more complex local functions at the top-level,
and once I'm happy with it I perform some re-factoring and move it in.


I would not write large local functions at all. I would leave them
top-level but do not export them. This also allows to test them from GHCi.


The downside to this is when you want to use the worker/wrapper 
transform in order to capture some local variables for a recursive 
function, instead of passing them through the recursion.


--
Live well,
~wren

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


[Haskell-cafe] Patch: adding CTR, CMAC and SIV modes to the Crypto API

2011-04-08 Thread klondike
Hi,

After a few weeks of hard work I have managed to add the CTR, CMAC and
SIV modes of operation. The implemententation passes all the KATS I
could find and is made as efficiently as possible without forgetting the
risk of timing attacks over them. The patch is attached here and you can
free it along with your library  with a BSD-3 license as long as you
recognize  the authorship.

Francisco Blas Izquierdo Riera (klondike)

PS: Attached is also a set of commands I used with ghci to check quickly
the implementation and which contain parts of the KATS I used, feel free
to use them.

diff -ur crypto-api-0.5.2/Crypto/Modes.hs crypto-api-0.5.2.new/Crypto/Modes.hs
--- crypto-api-0.5.2/Crypto/Modes.hs2011-02-16 17:46:11.0 +0100
+++ crypto-api-0.5.2.new/Crypto/Modes.hs2011-04-09 01:44:06.743745436 
+0200
@@ -12,7 +12,7 @@
(
-- * Initialization Vector Type (for all ciphers for all modes that use 
IVs)
  IV
-   , getIV, getIVIO
+   , getIV, getIVIO, zeroIV
-- * Blockcipher modes of operation.  Note name' (with a prime) means 
strict, without a prime means lazy bytestrings.
, ecb, unEcb
, cbc, unCbc
@@ -28,7 +28,9 @@
-- , gmc
-- , xts
-- , ccm
-   -- , ctr, unCtr, ctr', unCtr'
+   , cMac', cMac
+   , ctr, unCtr, ctr', unCtr', incIV, dblIV
+   , siv, unSiv, siv', unSiv'
) where
 
 import qualified Data.ByteString as B
@@ -36,12 +38,15 @@
 import Data.Serialize
 import qualified Data.Serialize.Put as SP
 import qualified Data.Serialize.Get as SG
-import Data.Bits (xor)
+import Data.Bits 
(xor,shift,(..),(.|.),testBit,setBit,clearBit,Bits,complementBit)
 import Data.Tagged
 import Crypto.Classes
 import Crypto.Random
+import Crypto.CPoly
 import System.Crypto.Random (getEntropy)
 import Control.Monad (liftM)
+import Data.Word (Word8)
+import Data.List (genericDrop,genericReplicate,genericLength)
 #if MIN_VERSION_tagged(0,2,0)
 import Data.Proxy
 #endif
@@ -120,10 +125,10 @@
in (c:cs, ivFinal)
 
 cbcMac' :: BlockCipher k = k - B.ByteString - B.ByteString
-cbcMac' k pt = encode $ snd $ cbc' k (IV (B.replicate (blockSize `for` k) 0)) 
pt
+cbcMac' k pt = encode $ snd $ cbc' k zeroIV pt
 
 cbcMac :: BlockCipher k = k - L.ByteString - L.ByteString
-cbcMac k pt = L.fromChunks [encode $ snd $ cbc k (IV (B.replicate (blockSize 
`for` k) 0)) pt]
+cbcMac k pt = L.fromChunks [encode $ snd $ cbc k zeroIV pt]
 
 -- |Cipher block chaining decryption for strict bytestrings
 unCbc' :: BlockCipher k = k - IV k - B.ByteString - (B.ByteString, IV k)
@@ -261,6 +266,253 @@
newIV = IV . B.concat . L.toChunks . L.take (fromIntegral ivLen) . 
L.drop mLen . L.fromChunks $ ivStr
in (zwp' (B.concat ivStr) msg, newIV)
 
+-- |Counter mode for lazy bytestrings
+ctr :: BlockCipher k = (IV k - IV k) - k - IV k - L.ByteString - 
(L.ByteString, IV k)
+ctr = unCtr
+
+-- |Counter  mode for lazy bytestrings
+unCtr :: BlockCipher k = (IV k - IV k) - k - IV k - L.ByteString - 
(L.ByteString, IV k)
+unCtr f k (IV iv) msg =
+   let ivStr = iterate f $ IV iv
+   ivLen = fromIntegral $ B.length iv
+   newIV = head $ genericDrop ((ivLen - 1 + L.length msg) `div` ivLen) 
ivStr
+   in (zwp (L.fromChunks $ map (encryptBlock k) $ map initializationVector 
ivStr) msg, newIV)
+
+-- |Counter mode for strict bytestrings
+ctr' :: BlockCipher k = (IV k - IV k) - k - IV k - B.ByteString - 
(B.ByteString, IV k)
+ctr' = unCtr'
+
+-- |Counter mode for strict bytestrings
+unCtr' :: BlockCipher k = (IV k - IV k) - k - IV k - B.ByteString - 
(B.ByteString, IV k)
+unCtr' f k (IV iv) msg =
+   let ivStr = iterate f $ IV iv
+   ivLen = fromIntegral $ B.length iv
+   newIV = head $ genericDrop ((ivLen - 1 + B.length msg) `div` ivLen) 
ivStr
+   in (zwp' (B.concat $ collect (B.length msg) (map (encryptBlock k . 
initializationVector) ivStr)) msg, newIV)
+
+-- |Generate cmac subkeys
+-- |The usage of seq tries to force evaluation of both keys avoiding posible 
timing attacks
+cMacSubk :: BlockCipher k = k - (IV k, IV k)
+cMacSubk k = (k1, k2) `seq` (k1, k2)
+  where
+   bSize = blockSizeBytes `for` k
+   k1 = dblIV $ IV $ encryptBlock k $ B.replicate bSize 0
+   k2 = dblIV $ k1
+
+-- |Pad the string as required by the cmac algorithm. In theory this should 
work
+-- | at bit level but since the API works at byte level we do the same
+cMacPad :: ([Word8], Bool, Int) - Maybe (Word8,([Word8], Bool, Int))
+cMacPad (_, _, 0) = Nothing
+cMacPad ([], False, n) = Just (0,([], False, n-1))
+cMacPad ([], True, n) = Just (128,([], False, n-1))
+cMacPad (x:xs, b, n) =  Just (x,(xs, b, n-1))
+
+-- |Obtain the cmac with the specified subkey for lazy bytestrings
+cMacWithSubK :: BlockCipher k = k - (IV k, IV k) - L.ByteString - 
L.ByteString
+cMacWithSubK k (IV k1, IV k2) l = L.fromChunks $ [go (chunkFor k t) $ 
B.replicate bSize1 0]
+  where
+   bSize1 = fromIntegral $ blockSizeBytes 

Re: [Haskell-cafe] Is there a way to find out the type inferred for a local function inside another function? :)

2011-04-08 Thread Evan Laforge
 I would not write large local functions at all. I would leave them
 top-level but do not export them. This also allows to test them from GHCi.

 The downside to this is when you want to use the worker/wrapper transform in
 order to capture some local variables for a recursive function, instead of
 passing them through the recursion.

I do this a lot too, but it doesn't mean you have to have large
functions.  The type of the worker is usually pretty trivially derived
from the type of wrapper, e.g.

wrapper :: A - B - C - D
wrapper a b = go 0
  where go n c = 

I've had a couple of cases with large functions with large numbers of
parameters that have a complicated recursion pattern and those are
indeed hard to factor into top level functions because each internal
definition uses a random assortment of variables (not necessarily
worker/wrapper either).  I suppose a refactoring editor could pull
inner definitions up to the top level and push them back down, but
hopefully those hairball functions are not common.

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe