Menu Close

Suma de cadenas

Definir la función

   sumaCadenas :: String -> String -> String

tal que (sumaCadenas xs ys) es la cadena formada por el número entero que es la suma de los números enteros cuyas cadenas que lo representan son xs e ys; además, se supone que la cadena vacía representa al cero. Por ejemplo,

   sumaCadenas "2"   "6"  == "8"
   sumaCadenas "14"  "2"  == "16"
   sumaCadenas "14"  "-5" == "9"
   sumaCadenas "-14" "-5" == "-19"
   sumaCadenas "5"   "-5" == "0"
   sumaCadenas ""    "5"  == "5"
   sumaCadenas "6"   ""   == "6"
   sumaCadenas ""    ""   == "0"

Soluciones

-- 1ª solución
-- ===========
 
sumaCadenas1 :: String -> String -> String
sumaCadenas1 xs ys =
  show (sum (map read (filter (not . null) [xs, ys])))
 
-- 2ª solución
-- ===========
 
sumaCadenas2 :: String -> String -> String
sumaCadenas2 =
  ((show . sum . map read . filter (not . null)) .) . (. return) . (:)
 
-- 3ª solución
-- ===========
 
sumaCadenas3 :: String -> String -> String
sumaCadenas3 "" "" = "0"
sumaCadenas3 "" ys = ys
sumaCadenas3 xs "" = xs
sumaCadenas3 xs ys = show (read xs + read ys)
 
-- 4ª solución
-- ===========
 
sumaCadenas4 :: String -> String -> String
sumaCadenas4 xs ys = show (numero xs + numero ys)
 
-- (numero xs) es el número entero representado por la cadena xs
-- suponiendo que la cadena vacía representa al cero.. Por ejemplo,
--    numero "12"   ==  12
--    numero "-12"  ==  -12
--    numero "0"    ==  0
--    numero ""     ==  0
numero :: String -> Int
numero "" = 0
numero xs = read xs

El código se encuentra en GitHub.

7 soluciones de “Suma de cadenas

  1. Adán Bonilla
    sumaCadenas :: String -> String -> String
    sumaCadenas xs ys =
      show (sum (map read (filter (not . null) [xs, ys])))
    • Adán Bonilla
      sumaCadenas :: String -> String -> String
      sumaCadenas = ((show . sum . map read . filter (not . null)) .) . (. return) . (:)
  2. j0sejuan
    import Safe (readDef)
     
    sumaCadenas xs ys = show (readDef 0 xs + readDef 0 ys)
  3. Blanca Castro
    def sumaCadenas(a, b):
        return str(int(a or 0) + int(b or 0))
  4. Carmen Domínguez
    sumaCadenas :: String -> String -> String
    sumaCadenas "" "" = "0"
    sumaCadenas "" ys = ys
    sumaCadenas xs "" = xs
    sumaCadenas xs ys = show (read xs + read ys)
  5. Eduardo Fernández
    sumaCadenas :: String -> String -> String
    sumaCadenas xs ys = show (aux xs + aux ys)
      where aux "" = 0
            aux xs = read xs
  6. Felipe Guerrero
    def sumaCadenas(*cs):
        return str(sum(int(c or '0') for c in cs))

Escribe tu solución

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.