0votos

Ecuación de primer grado en Haskell

por josejuan hace 6 años

Raro que nadie postee una en Haskell. Esta es una transcripción casi literal de la otra en C. Mejoras son usar directamente el tipo Rational y meter el acumulador como mónada. ¡Dedicada a jneira! :)

Resolución de ecuación de primer grado

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import Data.Ratio -- sólo se usa para devolver el resultado 
 
-- solver 
solve xs = -u % v 
    where    (a, b, c, ys) = l1 xs 
        (d, e, f, _) = l1 $ tail ys 
        (u, v) = (a * f - c * d, b * f - c * e) 
 
-- parser 
l1 ('(':xs) = (a, b, c, tail ys) where (a, b, c, ys) = l2 xs 
l1 xs = (a, b, c, ys) where (a, b, c, ys) = l2 xs 
 
l2 = l2a . l3a 
l2a (a, b, c, '-':xs) = (a * f - c * d, b * f - c * e, c * f, ys) where (d, e, f, ys) = l2 xs 
l2a (a, b, c, '+':xs) = (a * f + c * d, b * f + c * e, c * f, ys) where (d, e, f, ys) = l2 xs 
l2a (a, b, c, xs) = (a, b, c, xs) 
 
 
l3a ('-':xs) = (a, b, -c, ys) where (a, b, c, ys) = l3a xs 
l3a xs = l3b ys (a, b, c) where (a, b, c, ys) = lnum xs 
 
l3b [] (a, b, c) = (a, b, c, []) 
l3b (x:xs) (a, b, c) =    if x `elem` "x(0123456789" then 
                l3b ys (a * d, a * e + b * d, c * f) 
            else 
                if x == '/' then 
                    l3b zs (g, h, i) 
                else 
                    (a, b, c, x:xs) 
            where    (d, e, f, ys) = lnum (x:xs) 
                (g, h, i, zs) = l3c xs (a, b, c) 
 
l3c ('-':xs) (a, b, c) = (a, b, -c, xs) 
l3c xs (a, b, c) = (a * f, b * f, c * d, ys) where (d, e, f, ys) = lnum xs 
 
lnum ('x':xs) = (0, 1, 1, xs) 
lnum ('(':xs) = l1 ('(':xs) 
lnum xs = lnumN xs [] 
 
lnumN :: String -> String -> (Int, Int, Int, String) 
lnumN [] k = (read k, 0, 1, []) 
lnumN (x:xs) k = if x `elem` "0123456789" then lnumN xs (k++[x]) else (read k, 0, 1, x:xs) 
 
--================================================================================================ 
--================================================================================================ 
-- tests 
*Main> solve "x-13x/12=5x/18+13/12" 
(-3) % 1 
*Main> solve "3(11x/6-x)-4=2x-3(1-x/6)" 
*** Exception: Ratio.%: zero denominator 
*Main> solve "3x/4-1=x-(1-5x)2" 
4 % 41 
*Main> solve "x-(3-x)/3=3x/2-(8-3x)/4" 
12 % 11 

Comenta la solución

Tienes que identificarte para poder publicar tu comentario.