[Haskell-beginners] How best to do this?

Mateusz Kowalczyk fuuzetsu at fuuzetsu.co.uk
Mon Apr 29 16:54:26 CEST 2013


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 29/04/13 15:37, emacstheviking wrote:
> Benjamin, I have managed to reduce it all to this for which I thank
> you, it feels much neater now...
> 
> doOption dev (Forward n)  = do putStrLn $ "> STEP FORWARD " ++
> (show n) forM_ [3..0] (\b -> stepBit dev ioPORTA b)
> 
> doOption dev (Backward n) = do putStrLn $ "> STEP BACKWARD " ++
> (show n) forM_ [0..3] (\b -> stepBit dev ioPORTA b)
> 
> stepBit :: HWHandle -> Word8 -> Word8 -> IO () stepBit dev p b =
> setBit p b 0 >> setBit p b 1 where setBit p b s = HW.setPortBit dev
> p b s >> stepDelay
> 
> 
> I think I will also try to use "forEach_" as well which means I can
> then compose is something that passes in [0..3] or [3..0] to the
> composition... I may even learn something in the process! God I
> love the way that Haskell makes you *want* to reduce things to
> their most succint form, even if it hurts along the way. Only Lisp
> ever (ha, still does!) made me feel like Haskell does, aka a total
> n00b after 28 years in the business! LMAO
> 
> Thanks list.
> 

The next step would be to factor out that horrible repetition. Maybe
something like this:

doOption dev x = case x of
  (Backward n) -> stepper "FORWARD"
  (Forward n) -> stepper "BACKWARD"
  where stepper w = do
          putStrLn $ "> STEP " ++ w ++ (show n)
          forM_ [0 .. 3] (\b -> stepBit dev ioPORTA b)

I think this should work. It's also easier to introduce more options
this way.

- -- 
Mateusz K.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.19 (GNU/Linux)

iQIcBAEBAgAGBQJRfomiAAoJEM1mucMq2pqXpc8P/1X+snuFWZkprraX0UAZ95e7
pvCGelnxxW2rN1iUolzM5rD6MYBKTBhEMBp+SALrdQ3xUIYk/EP1yRfKnxJITe1g
CN08XqUcX47QMtmxQPvngKITT1L+voAL0DSei225ohT/lMIwetfbJuXub9iKzZ/G
YwLenR3R2E6iznys/Z/93Kk9tP5fXrOEkAFurqhe+xYTQnvDTMClv9cYEAj4xB1f
6x9gfqt5MbvJSyJ4PrGkJtXmS4RGSrysR5Eccf2p9CETlbBEo3uBHpzAPmqGXDFs
nfeuBoWxMb/X1w9ABim/i0pITR25S+XHG9HAlQNZ3jikY057Ict9YIr7xYkFjsPh
PEwVPlbf3QOTJW3IBXMbVTjA7yPiJnjG/tgAB3b8NYQnVfgPAQ/g7bw77pfm9W6X
ajbXgQ9slPADhG4vEKr7ktT8CD+DlOcm/iBYockQe3h6RoFSsRFSSoCOCM8ogPUl
xWp7wlZeRnP4AGB+R5vSHd06Fzk60L7D7vJvgTLINjqvhWGNrcVhvkEsCm9MWXEM
/rdqnbPBuUM3qz0MQnxWHvLeXgAIP5SzYxv2FthXlF+00/1Emqr1vk2F27mppDfZ
Xy/PUDjYTSHLCgPNvHVLyE9xfyVAPyqM2TarBrn8jyvi5Bx7WDn++4POD5B39MvM
TD57PLQJLg0oVrrLFnYQ
=Mbcq
-----END PGP SIGNATURE-----



More information about the Beginners mailing list