Ir al contenido principal

Haskell for Todos 2

 

Algunos ejercicios hechos en Haskell.

Haskell

Haskell es un lenguaje de programación estandarizado puramente funcional con semántica no estricta, llamado así por el lógico Haskell Curry. Es uno de los lenguajes funcionales más populares y el lenguaje funcional perezoso en el que se está realizando la mayor parte de la investigación.

Programando con Haskell

Extensión: *.hs y *.lhs

Compilar

$ ghc holamundo.hs

Ejecutar

$ ./holamundo

Abrir el REPL

Cargar script

$ ghci
> 12 + 45
> [1,2,3,4,5]
> let x = [3,9,6]
> :cd RUTA_DEL_SCRIPT
> :l script.hs
> :! clear
> :q

Operaciones básicas

$ ghci
> rem 120 100
> 12 + 54
> "Hola, mundo mundial del mundo universal"
> not True
> not False
> True || True
> False || True
> True && True
> False && True
> not (True || True)
> not (9/=3)
> 8/=6
> let nombre ="Juan Ortiz"
> nombre
> "Juan Pablo"/=nombre
> "Dan "++"Kerr"
> nombre++" Alvarez"
> let lista = [1,2,3]
> length lista
> head lista
> tail lista
> let cierto = if 7>3 then "X" else "Y"
> cierto
> :! clear
> :! pwd
> :! ls
> :q

Comentarios

--Este es un simple comentario en Haskell

Comentarios multilínea

{-
  Este es
     un comentario
   multi línea en
   Haskell
-}

sumar.hs

add :: Integer -> Integer -> Integer
add x y = x+y
{-
 $ ghci
 > :cd RUTA_DEL_SCRIPT
 > :l sumar.hs
 > sumar 4 5 --9
 > sumar 6 2 --8
-}

Síntaxis básica para crear una función

-- definimos función
nombreFunc :: Tipo -> Tipo ->Tipo
nombreFunc x 0 = x
nombreFunc 0 y = y
nombreFunc x y = x - y

Estructuras selectivas

if 2 > 0
	then "Verdadero: 2 es mayor a cero"
	else "Falso: 2 es menor a cero"
let decide = if 2 > 0 then "Verdadero: 2 es mayor a cero" else "Falso: 2 es menor a cero"

Sitio oficial:

view raw README.md hosted with ❤ by GitHub
import System.Environment
main = do
args <- getArgs
putStrLn "Los argumentos son:"
mapM_ putStrLn args
view raw argumentos.hs hosted with ❤ by GitHub
import System.Environment
main = do
args <- getArgs
file <- if null args
then do putStr "Archivo: " ; getLine
else pure (head args)
putStr "Procesando..."
putStrLn file
writeFile file "Hoy es 25 de abril de 2021"
{-
$ ghc argumentos_print.hs
$ ./argumentos_print archivo.dat
-}
main = do
let sueldo=9000
let edo_civil="soltero"
putStrLn("Sueldo inicial: "++show sueldo)
--funciones
--let aumento sueldo = (0.25*sueldo) + sueldo
--let bono sueldo = sueldo + 900
--let total b s = b + s
--putStrLn("Aumento: "++show(aumento(sueldo)))
--putStrLn("Bono: "++show(bono(sueldo)))
if sueldo < 10000
then
do
let aumento sueldo = (0.25*sueldo) + sueldo
--let bono sueldo = sueldo + 900
--putStrLn("Bono: "++show(bono(sueldo)))
putStrLn("Aumento: "++show(aumento(sueldo)))
--let total bono aumento = bono + aumento
--putStrLn("Sueldo final: "++show(total(bono,aumento)))
else
putStrLn "El sueldo es mayor o igual a 10000. No recibe aumento."
if edo_civil == "casado"
then
do
let bono sueldo = sueldo + 900
putStrLn("Bono: "++show(bono(sueldo)))
else
putStrLn "El empleado es casado. No recibe bono."
view raw aumento.hs hosted with ❤ by GitHub
{-
No. combinatorio
-}
fact :: Int -> Int
fact 0 = 1
fact n = fact(n-1)*n
combinatorio :: Int -> Int -> Int
combinatorio x 0 = 0
combinatorio 0 y = 0
combinatorio x y = fact(x) `div` fact(x)*fact(x-y)
-- Uso:
{-
$ ghci
> :cd RUTA_SCRIPT
> :l combinatorio.hs
> combinatorio 10 3
-}
view raw combinatorio.hs hosted with ❤ by GitHub
{-
Esto es un comentario multilinea en Haskell
[1,2,3] == [1,2,3] = True
[1,2] == [1,2,3] = False
[] == [1,2] = False
[1,2,3] == [] = False
-}
{-
*Main> comp_listas [1] []
False
*Main> comp_listas [1] [1]
True
*Main> comp_listas [1,2] [2,1]
False
*Main> comp_listas [] [2,1]
False
*Main> comp_listas [] [1]
False
*Main> comp_listas [32] [30+2]
True
-}
comp_listas :: [Int] -> [Int] -> Bool
comp_listas [] [] = True
comp_listas [] _ = False
comp_listas _ [] = False
comp_listas (a:b) (c:d) | (a == c) = comp_listas b d
| otherwise = False
view raw comparar.hs hosted with ❤ by GitHub
cubo :: Int -> Int
cubo num = num * num * num
view raw cubo.hs hosted with ❤ by GitHub
cuentaCifras lista = [if num<10 then "Una cifra" else "Dos cifras"
| num <- lista
, odd num]
view raw cuentaCifras.hs hosted with ❤ by GitHub
decide :: Int -> String
decide x = if x > 0
then "Verdadero: "++ show x ++" es mayor a cero"
else "Falso: "++show x++" es igual a cero"
view raw decide.hs hosted with ❤ by GitHub
divisible x y = if (x `mod` y) == 0
then "son divisibles"
else "no son divisibles"
view raw divisible.hs hosted with ❤ by GitHub
doubleSmall x = if x > 100
then x
else x*2
view raw doubleSmall.hs hosted with ❤ by GitHub
$ ghci
> :?
> :! pwd
> :cd /home/user/Documentos/scripts
> :! cat funcion.hs
> :l programa.hs
> programa variable
> :! clear
> :! ls
> :edit programa.hs
> :list
view raw ejecutar.txt hosted with ❤ by GitHub
esMayor x y = if x > y
then show x ++" es mayor"
else show y ++" es mayor"
view raw esMayor.hs hosted with ❤ by GitHub
euler :: Double -> Double
euler 0.0 = 1.0
euler n = 1.0 / product [1..n] + euler (n - 1.0)
view raw euler.hs hosted with ❤ by GitHub
factorial 0 = 1
factorial n = factorial(n-1)*n
view raw factorial.hs hosted with ❤ by GitHub
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci(n-1) + fibonacci(n-2)
view raw fibonacci.hs hosted with ❤ by GitHub
func :: (Int, Int) -> (Int, Int) -> (Int, Int)
func (a, b) (c, d) = (a+c, b+d)
view raw funcion.hs hosted with ❤ by GitHub
sumaCinco :: Int -> Int
sumaCinco x = x+5
multiplicaPorTres :: Int -> Int
multiplicaPorTres x = x*3
funcionDeAltoOrden f g x = f(g(x))
{-
$ ghci
> :cd RUTA_SCRIPT
> :l funciones.hs
> funcionDeAltoOrden multiplicaPorTres sumaCinco 6
33
-}
view raw funciones.hs hosted with ❤ by GitHub
{-
Fundamentos en Haskell
1. Entrar al shell (repl)
$ ghci
> :cd /home/fernando/Documentos/pruebasHaskell
> :l
> :q -- Salir del shell
-}
{-
5.
-}
{-
4. Creando tipos
-}
type Entero = Int
triple :: Entero -> Entero
triple 0 = 0
triple n = n * 3
{-
nombreFunc :: Tipo -> Tipo -> Tipo
nombreFunc a b = a + b
En lenguajes como Javascript sería:
function nombreFunc(a, b){
return a + b;
}
o
var nombreFunc = (a, b) => a+b;
-}
{-
RESULT=0
X=0
Y=1
IF X==0 THEN
RESULT = Y
END IF
IF Y==0 THEN
RESULT = X
END IF
IF X!=0 AND Y!=0 THEN
RESULT = X+Y
END IF
3. Crear funcion con dos parametros(x,y). Si x es 0, el resultado es y. Si y es 0, el resultado es x. Si ambos son distintos de 0, e resultado es la suma de x+y.
-}
nombreFunc :: Int -> Int -> Int
nombreFunc x 0 = x
nombreFunc 0 y = y
nombreFunc x y = x+y
{-
2. Función que devuelva 1 si el valor de entrada es 0
Ej.
factorial 0 = 1
factorial n = factorial(n-1)*n
En Javascript sería:
function factorial(num){
if(num <= 0){
return 1;
}else{
return factorial(num-1)*num;
}
}
let valor = factorial(0); // 1
valor = factorial(5);// 120
$ ghci
> :cd RUTA_SCRIPT
> :l fundamentos.hs
> verifica 0 -- 1
> verifica 2 -- 4
-}
verifica :: Int -> Int
verifica 0 = 1
verifica n = n*2
{-
-- 1. funciones
$ ghci
> :cd RUTA_SCRIPT
> :l fundamentos.hs
> sumaFunc 4 3
> restaFunc 4 5
> suma = sumaFunc 5 4
> suma
> resta = restaFunc 10 5
> resta
> operaFunc suma resta
-}
sumaFunc :: Int -> Int -> Int
sumaFunc x y = x+y
restaFunc :: Int -> Int -> Int
restaFunc x y = x-y
operaFunc :: Int -> Int -> Int
operaFunc x y = x*y
view raw fundamentos.hs hosted with ❤ by GitHub
guarda x | (x == 0) = 0
| (x == 1) = 1
| otherwise = 10
view raw guarda.hs hosted with ❤ by GitHub
hola :: IO()
hola = putStrLn "Hola, mundo en Haskell!!"
view raw hola.hs hosted with ❤ by GitHub
module Main where
main :: IO()
main = do
putStrLn "Hola, mundo en Haskell!!"
-- $ ghc holamonde.hs
-- $ ./holamonde
view raw holamonde.hs hosted with ❤ by GitHub
--Compilar: ghc holamundo.hs
--Ejecutar: ./holamundo
main = putStrLn "Bienvenido al mundo Haskell!"
view raw holamundo.hs hosted with ❤ by GitHub
siEsMayor m n = if m > n
then show m ++ " es mayor"
else show n ++ " es mayor"
{-
$ ghci
> :cd RUTA_SCRIPT
> :l if.hs
> siEsMayor 12 3
> siEsMayor 3 44
> :q
-}
{-
if 2 > 0
then "Verdadero: 2 es mayor a cero"
else "Falso: 2 es menor a cero"
-}
view raw if.hs hosted with ❤ by GitHub
--Obtener la longitud de una lista
longitud lista = sum[ 1 | x <-lista]
{-
$ ghci
> :cd RUTA_DEL_SCRIPT
> :l longitud.hs
> let lista = [1..30]
> longitud lista
> :q
-}
view raw longitud.hs hosted with ❤ by GitHub
mcd::Int->Int->Int
mcd x 0 = x
mcd x y = mcd y (mod x y)
{-
$ ghci
> :cd RUTA_SCRIPT
> :l maximocomundiv.hs
> mcd 3 4
> mcd 5 6
> :q
-}
my_and :: Bool -> Bool -> Bool
my_and False _ = False
my_and _ False = False
my_and True True = True
view raw my_and.hs hosted with ❤ by GitHub
nombres :: (String, String, String)
nombres = ("Fernando","Uriel", "Alma")
select_prim (x, _, _) = x
select_seg (_, y, _) = y
select_ter (_, _, z) = z
view raw nombres.hs hosted with ❤ by GitHub
type Nombre = String
type Edad = Int
type Idioma = String
type Persona = (Nombre, Edad, Idioma)
persona::Persona
persona = ("Horacio", 1994, "Portugues")
primero :: Persona -> Nombre
primero (n, e, i) = n
segundo :: Persona -> Edad
segundo (n, e, i) = e
tercero :: Persona -> Idioma
tercero (n, e, i) = i
view raw persona.hs hosted with ❤ by GitHub
primes = filterPrime [2..]
where filterPrime (p:xs) =
p : filterPrime [x | x <- xs, x `mod` p /= 0]
view raw primos.hs hosted with ❤ by GitHub
promedio :: Float -> Float -> Float
promedio a b = (a+b)/2.0
{-
$ ghci
> :cd RUTA_SCRIPT
> :l promedio.hs
> promedio 9 4
> 33.08 `promedio` 11.5 `promedio` 12.1
-}
view raw promedio.hs hosted with ❤ by GitHub
restar :: Int -> Int -> Int
restar 0 y = y
restar x 0 = x
restar x y = x - y
{-
$ ghci
> :cd /home/user/Documentos/pruebasHaskell
> :l restar.hs
> restar 3 2
> restar 10 5
-}
view raw restar.hs hosted with ❤ by GitHub
restoDeDosNum m n = m `mod` n
--author: Fer Carraro
main = do
putStrLn "Introduce tu nombre:"
nombre <- getLine
putStrLn("Hola, "++nombre)
--Esto es un comentario
view raw saludar.hs hosted with ❤ by GitHub
suma 1 = 1
suma n = suma(n-1) + n
view raw suma.hs hosted with ❤ by GitHub
suma :: Int -> Int -> Int
suma x y = x + y
{-
$ ghci
> :cd RUTA_SCRIPTS
> :l suma1.hs
> suma 3 4
> suma 8 3
-}
view raw suma1.hs hosted with ❤ by GitHub
sumaDiez x = x + 10
view raw sumaDiez.hs hosted with ❤ by GitHub
sumando :: Integer -> Integer -> Integer
sumando x y = x+y
{-
$ ghci
> :cd RUTA_DEL_SCRIPT
> :l sumando.hs
> sumando
-}
view raw sumando.hs hosted with ❤ by GitHub
sumaNumeros x y = x + y
view raw sumaNumeros.hs hosted with ❤ by GitHub
sumaTres num = num + num + num
{-
$ ghci
> :cd RUTA_DEL_SCRIPT
> :l sumaTres
> sumaTres 9 --27
> sumaTres 88 --264
> :q
-}
view raw sumaTres.hs hosted with ❤ by GitHub
--listas
size_list [] = 0
size_list (x:xs) = 1 + size_list xs
view raw tam.hs hosted with ❤ by GitHub
verdadero :: Bool -> Bool -> Bool
verdadero x y = x && y
view raw verdadero.hs hosted with ❤ by GitHub
vocales frase = [ letra | letra <- frase,
letra `elem` ['a','e','i','o','u'] ]
{-
$ ghci
> :cd RUTA_DEL_SCRIPT
> :l vocales.hs
> let frase = "europa renacida"
> vocales frase
> :q
-}
view raw vocales.hs hosted with ❤ by GitHub
Enlaces: https://emanuelpeg.blogspot.com/search?q=haskell https://alquimistadecodigo.blogspot.com/search?q=haskell http://learn.hfm.io/

Comentarios

Entradas populares de este blog

Programación Windows Batch (CMD) parte 3

Crear ciclos para efectuar operaciones tediosas nos ahorrará tiempo para realizar otras tareas. En está ocasión veremos ciclos con FOR . ¿Cuál es la síntaxis de bucle FOR en Windows Batch? Si está dentro de un archivo *.bat : FOR %%variable IN (seq) DO operaciones Si lo ejecutamos en una terminal: FOR %variable IN (seq) DO operaciones Ejemplo 1 . Recorrer una secuencia de números del 0 al 5: recorrer.bat @ echo off FOR %%i in ( 0 1 2 3 4 5 ) DO echo Hola no. %%i pause Nos imprimirá en pantalla: Hola no. 0 Hola no. 1 Hola no. 2 Hola no. 3 Hola no. 4 Hola no. 5 ¿Puedo usar contadores? Si, se pueden usar. Ejemplo 2 . Uso de contadores: contador.bat @ echo off set numeros = 1 2 3 4 5 6 7 8 9 10 set cont = 0 for %%a in ( %numeros% ) do ( echo Hola no. %%a :: Contador set /a cont+ = 1 ) echo Total: %cont% Este código nos imprimirá, además de los mensajes Hola no. 0 ..., el total de valores conta...

Programación Windows Batch (CMD) parte 4

Siguiendo con la serie de post sobre programación ( 1 , 2 , y 3 ) batch ahora veremos algunas cosas como operaciones aritméticas, operadores lógicos  y uso de ficheros. Cuando somos administradores de servidores o desarrolladores muchas veces tenemos que realizar tareas que nos quitan, relativamente, tiempo valioso que podríamos ocupar para otras cosas (como ver nuestro Facebook, jeje, broma).  Aprender a escribir scripts que nos faciliten algunas tareas siempre es útil. Por ejemplo, conocer todas las características técnicas de nuestro equipo de cómputo nos servirá cuando se realiza peritajes informáticos y soporte al equipo. Realizar respaldos automáticos a nuestras carpetas , archivos y directorios será más sencillo gracias a un script. Pero antes debemos aprender lo básico de la programación en batch. Ejemplo 1. Operaciones aritméticas básicas. aritmetica.bat @ echo off ::Nombre del archivo, imprimirá: aritmetica.bat echo %0 :: Set nos servirá para a...

COBOL para principiantes #1

COBOL es un lenguaje de programación que sigue dando de que hablar. Los programadores Java, C#, Python, etc. saben que aún existen aplicaciones hechas en COBOL y es difícil que éstas migren a un lenguaje más actual. Es por esa y otras razones que muchos han pensado en aprender este lenguaje 'obsoleto'. ¡COBOL is the king, no ha muerto! ¡A desempolvar los libros de nuestros abuelos, tíos o maestros! ¿Qué debemos hacer para aprender COBOL y no morir en el intento? Para empezar necesitas: Tener bases de programación (obvio). Conseguir un compilador dependiendo del sistema operativo que uses (si usas Windows puedes usar Visual Studio e instalar un compilador; si usas Linux puedes usar Gnu OpenCOBOL, nosotros usaremos éste último en el blog ). Saber qué extensión se usa para crear un programa COBOL (.cb, cbl, .cb). Nosotros usaremos .cbl  Comprender la estructura de un programa COBOL.  Conocer las estructuras de control y estructuras de datos en COBOL. Practicar...