Dmitriy Matrosov | 9 Feb 12:02
Picon
Gravatar

Relation between monads and computations

Hi, everyone!

Not so long ago i started to learn haskell, and now i have a question
about relation between monads and computations. In fact, i think, that
i understand it and write some explanation for myself, but i'm not
sure whether my explanation is correct or not, and will be very
thankful if someone check it :) Here it is (i don't know category
theory and my math knowledge is poor, so if i accidently use some
terms from them incorrectly - it was just my understanding).

Monads and computations.

Generally computation consists of initial value, computation itself and the
result. So it can be illustrated as:

    type    a         (M b)            b
    data    I ------>   C   <--------- E
                 f            ConstrM

    I :: a
    f :: a -> M b
    data M a = ContrM a | ...
    E :: b

Let's see what happens: i take initial value I of type a and map it to some
computation C (of type (M b)) using function f. Then, exist such value E of
type b, that C = (ConstrM E). This value E will be the result of computation.

Now consider two functions: unitM, which maps value into trivial computation
(trivial computation is a computation, which result is equal to initial
(Continue reading)

Adrien Haxaire | 6 Feb 10:31
Gravatar

Newtype to avoid orphans

 Hello,

 In the library I am writing, I declare a type Vector for Data.Vector 
 Double. I then create a Num instance for it as it doesn't have one yet. 
 GHC tells me that this instance is an orphan. After reading several 
 answers to issues like mine, I want to get rid of these orphans. The 
 advice I saw mostly is to use the newtype keyword.

 Is there a way to do it nicely, instead of copying most of the API of 
 Data.Vector ?

 Now, the only thing I can see is do like in this example:

 import Data.Vector as V

 newtype VectorD = VectorD (V.Vector Double)

 map :: (Double -> Double) -> VectorD -> VectorD
 map f (VectorD v) = VectorD $ V.map f v

 Is there a better way ?

 Best regards,
 Adrien

Picon
Gravatar

First program

Hello,

I am learning Haskell, and as a first program have made a JSON-RPC 
client library (code accessible here: 
https://patch-tag.com/r/Azel/hs-json-rpc/home). I would like to know if 
I have done great errors, be that errors of style or of library use.
Thanking you for your time.

Best regards,
ARJANEN Loïc

Thomas Engel | 5 Feb 09:19
Picon

numerical integration over lists

Hello,

I have two list (one with x values, the other with y values)
What I want to do is a numercial integration according the following formula:

Result x2 = Result x1 + ((y(x1) + y(x2))/2) * (x2 -x1)

and put the result in another list.

below my first try:

integriereListe::(a)->(a)->(a)
integriereListe [][]  = [0.0]
integriereListe (x:xs) (y:ys)   = ((y - y2) /2) * (x2 -x)
                                  where
                                  x2 = head xs
                                  y2 = head ys    

but I got the failure

 Couldn't match type `[t0]' with `[[t0]]'
    In the pattern: y : ys
    In an equation for `integriereListe':
        integriereListe (x : xs) (y : ys)
          = ((y - y2) / 2) * (x2 - x)
          where
              x2 = head xs
              y2 = head ys

another problem is how get the result  x1 (see above)
(Continue reading)

Thomas Engel | 4 Feb 19:34
Picon

Re: nested guards (Stephen Tetley)

> > http://www.haskell.org/haskellwiki/Case
> >
> > That link shows how to write a select function that offers functionality
> > similar to a switch statement in C. ?Then you could use guards for the
> > top-level switching and the select function for the second level.
> 
> Yikes - that idiom is rather horrible, vis packing cases into a list
> so they can be consumed by a function.
> 
> To solve the problem, I'd seek a more "mathy" description of the
> algorithm i.e. one that doesn't use conditionals so heavily and work
> from that rather than translate existing code.
> 
Hi Stephen,

I have solved the problem. I have made four functions instead of one.
> 
> 
> Thanks
> 
> Thomas
> 

Ovidiu Deac | 4 Feb 11:49
Picon
Gravatar

yet another monad question

I have the following code which works fine:

type File = (String, String) --name and content

readDir :: String -> IO [File]
readDir dir = findRegularFiles dir >>= readFiles
  where
    findRegularFiles = find always (fileType ==? RegularFile)
    readFiles paths = mapM readFile paths >>= return.zip paths

...and I would like to write the function readDir like this:
readDir :: String -> IO [File]
readDir = findRegularFiles >>= readFiles
  where ...

...but I get the error:
grep.hs:46:32:
    Couldn't match expected type `IO [FilePath]'
                with actual type `[FilePath]'
    Expected type: IO [FilePath] -> String -> IO [File]
      Actual type: [FilePath] -> IO [File]
    In the second argument of `(>>=)', namely `readFiles'
    In the expression: findRegularFiles >>= readFiles

Can somebody please explain it?

It's not a big deal. I can keep the old version which works fine. My only problem is that I thought I understood the monads better but apparently I don't :)
anyzhen | 4 Feb 11:36
Favicon
Gravatar

How memorize intermediate computation value[my brain is so hurt]?

there have a lot of situation we need memorize intermediate computation value. 
and use in further.
like this, compute nth fib question.
So,how memorize it?

i have an ugly solution.it used HashTable for memorization.

fib n table
 | n==1 =1
 | n==2 =1
 | otherwise =
  case lookup table of
    Just v   ->(v,table)
    Nothing ->let (v,table') = fib (n-1) table in
                   let ( v',table'')= v + fib(n-2) table' in
                   (v',table'')

i am an beginner come from imperative programming language.
so fib memorize version program hurt my brain ... particular in Nothing branches.
so do you have some good idea

Thomas Engel | 3 Feb 19:55
Picon

nested guards

Hello,

I'm new to haskell. I want to write a function for a s-curve acceleration in haskell.
A solution in VBA is already working.

Are there nested guards in haskell available or how can I rewrite this function?

The function should calculate the acceleration for a given distance, max acceleration, velocity, jerk at
time since start

acc_skurve::Float->Float->Float->Float->Float->Float
acc_skurve str acc v jerk taktuell
 | str <= str2jerk                  |taktuell <= (0.5 * str / jerk)**(1/3::Float)    = jerk * taktuell
                                    |taktuell <= (4 * str / jerk)**(1/3::Float)      = jerk**(2/3::Float) * 2**(2/3::Float) * str**(1/3::Float)
- jerk * taktuell
                                    |taktuell <= (27/2 * str / jerk)**(1/3::Float)   = - jerk * taktuell + 2**(2/3::Float) * str**(1/3::Float) * jerk**(2/3::Float)
                                    |taktuell <= (32 * str / jerk)**(1/3::Float)     = -2 * 2**(2/3::Float) * str**(1/3::Float) *
jerk**(2/3::Float) + jerk * taktuell
 | str > str2jerk && str < str2acc  |taktuell <= acc / jerk                                                                     = jerk * taktuell                                                                   
                                    |taktuell <= - acc / 2 / jerk + sqrt(acc^3 + 4 * str * jerk^2) / (2 * jerk * sqrt(acc))     = acc                                                                               
                                    |taktuell <=  acc / 2 / jerk + sqrt(acc^3 + 4 * str * jerk^2) / (2 * jerk * sqrt(acc))      = acc / 2 - jerk * taktuell +
sqrt(acc^3 + 4 * str * jerk^2) / (2 * sqrt(acc))      
                                    |taktuell <=  3 * acc / 2 / jerk + sqrt(acc^3 + 4 * str * jerk^2) / (2 * jerk * sqrt(acc))  = acc / 2 - jerk * taktuell +
sqrt(acc^3 + 4 * str * jerk^2) / (2 * sqrt(acc))  
                                    |taktuell <=  sqrt(acc^3 + 4 * str * jerk^2) / (sqrt(acc * jerk))                           = - acc                                                                                                  
                                    |taktuell <=  acc / jerk + sqrt(acc^3 + 4 * str * jerk^2) / (sqrt(acc * jerk))              = - acc + jerk * taktuell -
sqrt(acc^3 + 4 * str * jerk^2) / sqrt(acc)                      
 | str >= str2acc                   |taktuell <= acc / jerk                 = jerk * taktuell                                                                                                                   
                                    |taktuell <= v / acc                    = acc                                                      
                                    |taktuell <= acc / jerk + v / acc       = acc - jerk * taktuell + v * jerk / acc                   
                                    |taktuell <= str / v                    = 0                                                        
                                    |taktuell <= str / v + acc / jerk       = jerk * str / v - jerk * taktuell                         
                                    |taktuell <= str / v + v / acc          = - acc                                                    
                                    |taktuell <= str / v + acc / jerk + v / acc = -(str / v + acc / jerk + v / acc - taktuell) * jerk  
   where str2jerk = 2 * acc^2 / jerk^2
         str2acc  = acc^2 * v + v^2 * jerk / (jerk * acc)

best regards
Thomas

Thomas Engel | 3 Feb 19:43
Picon

(no subject)


Zhi-Qiang Lei | 2 Feb 17:16
Picon

Is foldr slow?

Hi,

When I refactor my Segmented Seive of Eratosthenes, I'm puzzled by the performance of "foldr".
Here is my original code. I realized that "sieveWith"(Integral a => ([a], [a]) -> ([a], [a]), it takes a tuple with sieving primes and prime candidates, and remove all multiplies of sieving primes in candidates, at last return a tuple with blank sieving primes and a pure primes list) in "primesFromTo" is not much readable and can be replaced by "foldr".

But when I did, I find it would take about 5 seconds to sieve primes between 999900000 and 1000000000, whereas the original one just takes 1.6 
seconds. The "sieveWith" function is the only place I change. I also have tried foldr', which does not much help. Is foldr slow? Or did I make any 
mistake? Thanks.

=== Origin (./main < data1.txt  1.45s user 0.11s system 99% cpu 1.562 total) ===
{-# OPTIONS_GHC -O2 #-}

import Data.List
import System.IO

minus (x:xs) (y:ys) = case (compare x y) of 
           LT -> x : minus  xs  (y:ys)
           EQ ->     minus  xs     ys 
           GT ->     minus (x:xs)  ys
minus  xs     _     = xs

intSqrt :: Integral a => a -> a
intSqrt = floor . sqrt . fromIntegral

primesTo :: Integral a => a -> [a]
primesTo x = 2 : sieve [3, 5 .. x] where
    sieve ns <at> (n : rs)
        | n <= intSqrt x    = n : sieve (rs `minus` [n * n, n * (n + 2) .. x])
        | otherwise         = ns
    sieve [] = []

candidatesBetween :: Integral a => a -> a -> [a]
candidatesBetween x y = let x' = if odd x then x else x + 1 in [x', x' + 2 .. y]

primesFromTo :: Integral a => a -> a -> [a]
primesFromTo x y
    | x < 2 = primesTo y
    | otherwise = snd . sieveWith $ (primes, candidates) where
        primes = tail . primesTo . intSqrt $ y
        candidates = candidatesBetween x y
        sieveWith (a : as, bs' <at> (b : bs)) = sieveWith (as, bs' `minus` multiplies a b) where
        sieveWith ([], bs) = ([], bs)
        multiplies a b = let b' = b + ((-b) `mod` a) in [b', b' + 2 * a .. y]

primesFromTo' [x, y] = primesFromTo x y

main :: IO ()
main = do
    count <- fmap read getLine
    inputLines <- fmap (take count . lines) getContents
    let answers = map (primesFromTo' . map read . words) inputLines
    putStr . unlines . map (unlines . map show) $ answers

=== Origin ===

=== New (./main < data1.txt  4.76s user 0.15s system 99% cpu 4.917 total) ===
{-# OPTIONS_GHC -O2 #-}

import Data.List
import System.IO

minus (x:xs) (y:ys) = case (compare x y) of 
           LT -> x : minus  xs  (y:ys)
           EQ ->     minus  xs     ys 
           GT ->     minus (x:xs)  ys
minus  xs     _     = xs

intSqrt :: Integral a => a -> a
intSqrt = floor . sqrt . fromIntegral

primesTo :: Integral a => a -> [a]
primesTo x = 2 : sieve [3, 5 .. x] where
    sieve ns <at> (n : rs)
        | n <= intSqrt x    = n : sieve (rs `minus` [n * n, n * (n + 2) .. x])
        | otherwise         = ns
    sieve [] = []

candidatesBetween :: Integral a => a -> a -> [a]
candidatesBetween x y = let x' = if odd x then x else x + 1 in [x', x' + 2 .. y]

primesFromTo :: Integral a => a -> a -> [a]
primesFromTo x y
    | x < 2 = primesTo y
    | otherwise = sieveWith primes candidates where
        primes = tail . primesTo . intSqrt $ y
        candidates = candidatesBetween x y
        -- sieve a list of candidates with sieving primes
        -- foldr version: ./main < data1.txt  4.76s user 0.15s system 99% cpu 4.917 total
        sieveWith ps' <at> (p : ps) cs' <at> (c : cs) = foldr (\a b -> b `minus` (multiplies a c)) cs' ps'
        sieveWith [] cs = cs
        multiplies a b = let b' = b + ((-b) `mod` a) in [b', b' + 2 * a .. y]

primesFromTo' [x, y] = primesFromTo x y

main :: IO ()
main = do
    count <- fmap read getLine
    inputLines <- fmap (take count . lines) getContents
    let answers = map (primesFromTo' . map read . words) inputLines
    putStr . unlines . map (unlines . map show) $ answers

=== New ===

Best regards,
Zhi-Qiang Lei

Ovidiu Deac | 2 Feb 03:28
Picon
Gravatar

unchecked exceptions as side effects

In this video Erik Meijer talks about side effects: https://www.youtube.com/watch?v=UuamC0T3hv8&t=6m and unchecked exceptions as side effects.

I tried to read the paper "Unchecked Exceptions can be Strictly More Powerful than Call/CC" but I got lost pretty quick.

Can somebody explain the matter nicely?

Thanks,
ovidiu


Gmane