From 5be296e5b2b0f6ef9355b9d1cf9d0a7947a67094 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Sat, 23 Nov 2013 17:01:14 -0200 Subject: Add translate until list comprehensions I'm translating haskell guide from Adit Bhargava (learnxinyminutes contribuitor) but adding a few more stuff about haskell --- pt-br/haskell-pt.html.markdown | 439 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 439 insertions(+) create mode 100644 pt-br/haskell-pt.html.markdown (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown new file mode 100644 index 00000000..ca0d847c --- /dev/null +++ b/pt-br/haskell-pt.html.markdown @@ -0,0 +1,439 @@ +--- +linguagem: haskell +tradutor/contribuidor: + - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] +--- + +As linguagens funcionais são linguagens de programação com base em avaliação +de funções matemáticas (expressões), evitando-se o conceito de mudança de +estado com alteração de dados. Neste aspecto, este paradigma é oposto ao +paradigma imperativo que se baseia em alterações de estados. + +A programação funcional começou no cálculo lambda, que foi base teórica para +o desenvolvimento deste paradigma de programação. + + +```haskell +-- Para comentar a linha basta dois traços seguidos. + +{- Abre chaves traço e traço fecha chaves cria um campo + para comentário em múltiplas linhas. +-} + +---------------------------------------------------- +-- 1. Tipos Primitivos de Dados e Operadores +---------------------------------------------------- + +-- Numerais + +0 -- 3 +1 -- 1 +2 -- 2 ... + +-- Alguns Operadores Fundamentais + +7 + 7 -- 7 mais 7 +7 - 7 -- 7 menos 7 +7 * 7 -- 7 vezes 7 +7 / 7 -- 7 dividido por 7 + +-- Divisões não são inteiras, são fracionádas por padrão da linguagem +28736 / 82374 -- 0.3488479374559934 + + +-- Divisão inteira +82374 `div` 28736 -- 2 + +-- Divisão modular +82374 `mod` 28736 -- 24902 + +-- Booleanos como tipo primitivo de dado +True -- Verdadeiro +False -- Falso + +-- Operadores unitário +not True -- Nega uma verdade +not False -- Nega uma falácia + + +-- Operadores binários +7 == 7 -- 7 é igual a 7 ? +7 /= 7 -- 7 é diferente de 7 ? +7 < 7 -- 7 é menor que 7 ? +7 > 7 -- 7 é maior que 7 ? + + +{- Haskell é uma linguagem que tem uma sintáxe bastante familiar na + matemática, por exemplo em chamadas de funções você tem: + + NomeFunção ArgumentoA ArgumentoB ArgumentoC ... +-} + +-- Strings e Caractéres +"Texto entre abre áspas e fecha áspas define uma string" +'a' -- Caractere +'A' -- Caractere + +'Strings entre aspas simples sobe um erro' -- Erro léxico! + +-- Concatenação de Strings +"StringA" ++ "StringB" -- "StringAStringB" + +-- Você pode listar uma string pelos seus caractéres +"AbBbbcAbbcbBbcbcb" !! 0 -- 'A' +"AbBbbcAbbcbBbcbcb" !! 1 -- 'b' +"AbBbbcAbbcbBbcbcb" !! 2 -- 'B' + +---------------------------------------------------- +-- Listas e Túplas +---------------------------------------------------- + +-- A construção de uma lista precisa ser de elementos homogêneos +[1, 2, 3, 4, 5] -- Homogênea +[1, a, 2, b, 3] -- Heterogênea (Erro) + +-- Haskell permite que você crie sequências +[1..5] + +{- Haskell usa avaliação preguiçosa o que + Permite você ter listas "infinitas" +-} + +-- Uma lista "infinita" cuja razão é 1 +[1..] + +-- O 777º elemento de uma lista de razão 1 +[1..] !! 777 -- 778 + +-- União de listas [lista_0] ++ [lista_1] ++ [lista_i] +[1..5] ++ [6..10] ++ [1..4] -- [1,2,3,4,5,6,7,8,9,10,1,2,3,4] + +-- Adiciona um cabeçalho a sua lista e desloca a cauda +0:[1..10] -- [0, 1, 2, 3, 4, 5] +'a':['a'..'e'] -- "aabcde" + +-- Indexação em uma lista +[0..] !! 5 -- 5 + +-- Operadores de Listas usuais +head ['a'..'e'] -- Qual o cabeçalho da lista ? +tail ['a'..'e'] -- Qual a cauda da lista ? +init ['a'..'e'] -- Qual a lista menos o último elemento ? +last ['a'..'e'] -- Qual o último elemento ? + +-- list comprehensions +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- with a conditional +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Every element in a tuple can be a different type, but a tuple has a +-- fixed length. +-- A tuple: +("haskell", 1) + +-- accessing elements of a tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- A simple function that takes two variables +add a b = a + b + +-- Note that if you are using ghci (the Haskell interpreter) +-- You'll need to use `let`, i.e. +-- let add a b = a + b + +-- Using the function +add 1 2 -- 3 + +-- You can also put the function name between the two arguments +-- with backticks: +1 `add` 2 -- 3 + +-- You can also define functions that have no letters! This lets +-- you define your own operators! Here's an operator that does +-- integer division +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guards: an easy way to do branching in functions +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Pattern matching is similar. Here we have given three different +-- definitions for fib. Haskell will automatically call the first +-- function that matches the pattern of the value. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Pattern matching on tuples: +foo (x, y) = (x + 1, y + 2) + +-- Pattern matching on lists. Here `x` is the first element +-- in the list, and `xs` is the rest of the list. We can write +-- our own map function: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Anonymous functions are created with a backslash followed by +-- all the arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- using fold (called `inject` in some languages) with an anonymous +-- function. foldl1 means fold left, and use the first value in the +-- list as the initial value for the accumulator. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. More functions +---------------------------------------------------- + +-- currying: if you don't pass in all the arguments to a function, +-- it gets "curried". That means it returns a function that takes the +-- rest of the arguments. + +add a b = a + b +foo = add 10 -- foo is now a function that takes a number and adds 10 to it +foo 5 -- 15 + +-- Another way to write the same thing +foo = (+10) +foo 5 -- 15 + +-- function composition +-- the (.) function chains functions together. +-- For example, here foo is a function that takes a value. It adds 10 to it, +-- multiplies the result of that by 5, and then returns the final value. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fixing precedence +-- Haskell has another function called `$`. This changes the precedence +-- so that everything to the left of it gets computed first and then applied +-- to everything on the right. You can use `.` and `$` to get rid of a lot +-- of parentheses: + +-- before +(even (fib 7)) -- true + +-- after +even . fib $ 7 -- true + +---------------------------------------------------- +-- 5. Type signatures +---------------------------------------------------- + +-- Haskell has a very strong type system, and everything has a type signature. + +-- Some basic types: +5 :: Integer +"hello" :: String +True :: Bool + +-- Functions have types too. +-- `not` takes a boolean and returns a boolean: +-- not :: Bool -> Bool + +-- Here's a function that takes two arguments: +-- add :: Integer -> Integer -> Integer + +-- When you define a value, it's good practice to write its type above it: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Control Flow and If Statements +---------------------------------------------------- + +-- if statements +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- if statements can be on multiple lines too, indentation is important +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case statements: Here's how you could parse command line arguments +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell doesn't have loops because it uses recursion instead. +-- map applies a function over every element in an array + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- you can make a for function using map +for array func = map func array + +-- and then use it +for [0..5] $ \i -> show i + +-- we could've written that like this too: +for [0..5] show + +-- You can use foldl or foldr to reduce a list +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- This is the same as +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl is left-handed, foldr is right- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- This is now the same as +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Data Types +---------------------------------------------------- + +-- Here's how you make your own data type in Haskell + +data Color = Red | Blue | Green + +-- Now you can use it in a function: + + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" + +-- Your data types can have parameters too: + +data Maybe a = Nothing | Just a + +-- These are all of type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- While IO can't be explained fully without explaining monads, +-- it is not hard to explain enough to get going. + +-- When a Haskell program is executed, the function `main` is +-- called. It must return a value of type `IO ()`. For example: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () + +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function +-- interact :: (String -> String) -> IO () +-- inputs some text, runs a function on it, and prints out the +-- output. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- You can think of a value of type `IO ()` as representing a +-- sequence of actions for the computer to do, much like a +-- computer program written in an imperative language. We can use +-- the `do` notation to chain actions together. For example: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- this gets a line and gives it the name "name" + putStrLn $ "Hello, " ++ name + +-- Exercise: write your own version of `interact` that only reads +-- one line of input. + +-- The code in `sayHello` will never be executed, however. The only +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` +-- and replace it with: +-- main = sayHello + +-- Let's understand better how the function `getLine` we just +-- used works. Its type is: +-- getLine :: IO String +-- You can think of a value of type `IO a` as representing a +-- computer program that will generate a value of type `a` +-- when executed (in addition to anything else it does). We can +-- store and reuse this value using `<-`. We can also +-- make our own action of type `IO String`: + +action :: IO String +action = do + putStrLn "This is a line. Duh" + input1 <- getLine + input2 <- getLine + -- The type of the `do` statement is that of its last line. + -- `return` is not a keyword, but merely a function + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- We can use this just like we used `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- The type `IO` is an example of a "monad". The way Haskell uses a monad to +-- do IO allows it to be a purely functional language. Any function that +-- interacts with the outside world (i.e. does IO) gets marked as `IO` in its +-- type signature. This lets us reason about what functions are "pure" (don't +-- interact with the outside world or modify state) and what functions aren't. + +-- This is a powerful feature, because it's easy to run pure functions +-- concurrently; so, concurrency in Haskell is very easy. + + +---------------------------------------------------- +-- 9. The Haskell REPL +---------------------------------------------------- + +-- Start the repl by typing `ghci`. +-- Now you can type in Haskell code. Any new values +-- need to be created with `let`: + +let foo = 5 + +-- You can see the type of any value with `:t`: + +>:t foo +foo :: Integer + +-- You can also run any action of type `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). + +You can find a much gentler introduction from the excellent +[Learn you a Haskell](http://learnyouahaskell.com/) or +[Real World Haskell](http://book.realworldhaskell.org/). -- cgit v1.2.3 From 3d29112cab44b33cacf8b231968744862554dbc5 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Sun, 24 Nov 2013 21:45:30 -0200 Subject: Add traslate the topic more functions Extra-Add a topic about the refs and 'keep readings' --- pt-br/haskell-pt.html.markdown | 321 ++++++++++++++++++++++++++++------------- 1 file changed, 219 insertions(+), 102 deletions(-) (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index ca0d847c..3d80a44f 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -79,6 +79,10 @@ not False -- Nega uma falácia -- Concatenação de Strings "StringA" ++ "StringB" -- "StringAStringB" +-- Concatenação de Caracteres +"haskell" == ['h','a','s','k','e','l','l'] -- True +"haskell" == 'h':'a':'s':'k':'e':'l':'l':[] -- True + -- Você pode listar uma string pelos seus caractéres "AbBbbcAbbcbBbcbcb" !! 0 -- 'A' "AbBbbcAbbcbBbcbcb" !! 1 -- 'b' @@ -96,7 +100,7 @@ not False -- Nega uma falácia [1..5] {- Haskell usa avaliação preguiçosa o que - Permite você ter listas "infinitas" + permite você ter listas "infinitas". -} -- Uma lista "infinita" cuja razão é 1 @@ -121,81 +125,174 @@ tail ['a'..'e'] -- Qual a cauda da lista ? init ['a'..'e'] -- Qual a lista menos o último elemento ? last ['a'..'e'] -- Qual o último elemento ? --- list comprehensions -[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] +-- Compreensão de Lista (List Comprehension) + +{- Uma lista pode ser especificada + pela definição de eus elementos. + A compreensão de listas é feita + com um construtor de listas que + utiliza conceitos e notações + da teoria dos conjuntos. + + Exemplo: + + A = { x**2 | X pertence aos Naturais && x é par} +-} + +let par x = mod x 2 == 0 +let constroi_lista = [x * x | x <- [9 ..39], par x] +-- [100,144,196,256,324,400,484,576,676,784,900,1024,1156,1296,1444] --- with a conditional +par 4 -- True +par 3 -- False + + +-- Listas com regras +{- Para todo x se x é elemento da lista + faça 2 vezes x mas componha a lista + com apenas aqueles elementos cujo + 2*x é maior que 4 +-} [x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] --- Every element in a tuple can be a different type, but a tuple has a --- fixed length. --- A tuple: -("haskell", 1) +-- Tuplas +("Q", "Gamma", "b", "Sigma", "delta", "q0", "F") -- 7-Tuple Turing Machine + +-- Retirando da tupla + +{- Com as funções fst (primeiro) e snd (segundo) + você só pode enviar por parâmetro uma tupla + bi-dimensional ou seja, 2 dimensões == (x,y) +-} + +fst ((2,3), [2,3]) -- (2,3) +snd ((2,3), [4,3]) -- [4,3] --- accessing elements of a tuple -fst ("haskell", 1) -- "haskell" -snd ("haskell", 1) -- 1 ---------------------------------------------------- --- 3. Functions +-- 3. Funções em Haskell ---------------------------------------------------- --- A simple function that takes two variables -add a b = a + b --- Note that if you are using ghci (the Haskell interpreter) --- You'll need to use `let`, i.e. --- let add a b = a + b - --- Using the function -add 1 2 -- 3 - --- You can also put the function name between the two arguments --- with backticks: -1 `add` 2 -- 3 - --- You can also define functions that have no letters! This lets --- you define your own operators! Here's an operator that does --- integer division -(//) a b = a `div` b -35 // 4 -- 8 - --- Guards: an easy way to do branching in functions -fib x - | x < 2 = x - | otherwise = fib (x - 1) + fib (x - 2) - --- Pattern matching is similar. Here we have given three different --- definitions for fib. Haskell will automatically call the first --- function that matches the pattern of the value. -fib 1 = 1 -fib 2 = 2 -fib x = fib (x - 1) + fib (x - 2) - --- Pattern matching on tuples: -foo (x, y) = (x + 1, y + 2) - --- Pattern matching on lists. Here `x` is the first element --- in the list, and `xs` is the rest of the list. We can write --- our own map function: -myMap func [] = [] -myMap func (x:xs) = func x:(myMap func xs) - --- Anonymous functions are created with a backslash followed by --- all the arguments. -myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] - --- using fold (called `inject` in some languages) with an anonymous --- function. foldl1 means fold left, and use the first value in the --- list as the initial value for the accumulator. +-- Uma função simples que toma duas variáveis +{- Haskell trabalha em cima de recursão + Portanto certifique-se que você + Entende como recurssão funciona. +-} + +soma a b = a + b -- Função que vai em um programa.hs + +{- Dentro do GHCi (Interpretador Haskell) + Você terá que fazer da seguinte maneira-- Podemos criar nos + + Prelude> let soma a b = a + b + Prelude> soma 7 7 -- 14 +-} + +let constroi_lista = [x * x | x <- [9 ..39], par x] + +{- Você pode usar crases para chamar + Funcões de maneira diferente +-} + +7 `soma` 7 -- 14 + +{- Haskell permite que você crie os + seus próprios operadores baseados + nos já existendes +-} + +let (~/\) a b = a `mod` b +15^13 ~/\ 432 -- 759375 + +-- Casamento de Padrões em Tuplas +coordenadas (x, y) = (x + 13, y - 31) + +{- Haskell trabalha com casamento de padrões onde dada + um conjunto de funções definidas de diferentes maneiras + Haskell vai procurar por aquela que trabalha o seu tipo + de entrada. +-} + +-- Guardas "|" É um jeito simples de representar funções recursivas + +let fatorial n | n == 0 = 1 | otherwise = fatorial (n - 1) * n -- Teste: fatorial 5 + +-- Ainda podemos fazer: + +let fatorial 0 = 1 +let fatorial n = fatorial (n - 1) * n + +{- Podemos criar nossos próprios Mapeadores + Onde `primeiro` é o primeiro elemento de + uma lista é `resto` é o resto da lista. +-} + +mapa mapeador [] = [] +mapa mapeador (primeiro : resto) = mapeador primeiro : (mapa mapeador resto) + +{- Funções Anônimas são criadas com um `\` (barra invertida) + seguido por seus argumentos! +-} +mapa (\primeiro -> primeiro + 2) [1..5] -- [3, 4, 5, 6, 7] + +{- Usar "fold" (chamado `inject` em algumas outras línguagens) com + uma função anônima. + + significa E mapeia o primeiro valor + da lista para ser o acumulador. +-} foldl1 (\acc x -> acc + x) [1..5] -- 15 +foldl1 (\x y -> (x+y)/5) [7..55] -- 13.6875 + +---------------------------------------------------- +-- 4. Mais Funções +---------------------------------------------------- + +{- Currying: Se você não passar todos os argumentos + para uma função, ela irá ser "currificada". O que + significa que irá retornar a função que pega o resto + dos elementos. +-} + +soma a b = a + b +foo = soma 10 -- foo ganha a propriedade "currying" +foo 5 -- 15 + +-- Outra maneira +foo = (+10) +foo 5 -- 15 + +{- Composição de Funções + O (.) encadeia funções! Por exemplo, + aqui foo é uma função que recebe um valor. + Ela soma 10 a ela, multiplica o resultado por 5 + e então retorna o resultado final. +-} +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +{- Concertando precedência: + Haskell tem outra função chamada `$`. Isso altera a precedência + de computação. Ou seja Haskell computa o que está sendo sinalizado com $ + da esquerda para a direita . You can use `.` and `$` to get rid of a lot + of parentheses: +-} + +-- Antes +(even (fatorial 3)) -- true + +-- Depois +even . fatorial $ 3 -- true ---------------------------------------------------- -- 4. More functions ---------------------------------------------------- --- currying: if you don't pass in all the arguments to a function, --- it gets "curried". That means it returns a function that takes the --- rest of the arguments. +{- Mais Sobre Funções Currificadas: se você não passar + todos os argumentos para uma função. +-} add a b = a + b foo = add 10 -- foo is now a function that takes a number and adds 10 to it @@ -329,13 +426,13 @@ Nothing -- of type `Maybe a` for any `a` -- called. It must return a value of type `IO ()`. For example: main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) +main = putStrLn $ "Hello, sky! " ++ (say Blue) -- putStrLn has type String -> IO () --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function -- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the +-- inputs some text, runs a function on it, and prints out the -- output. countLines :: String -> String @@ -349,43 +446,43 @@ main' = interact countLines -- the `do` notation to chain actions together. For example: sayHello :: IO () -sayHello = do +sayHello = do putStrLn "What is your name?" name <- getLine -- this gets a line and gives it the name "name" putStrLn $ "Hello, " ++ name - + -- Exercise: write your own version of `interact` that only reads -- one line of input. - + -- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` -- and replace it with: -- main = sayHello --- Let's understand better how the function `getLine` we just +-- Let's understand better how the function `getLine` we just -- used works. Its type is: -- getLine :: IO String -- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` +-- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- store and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String action = do putStrLn "This is a line. Duh" - input1 <- getLine + input1 <- getLine input2 <- getLine -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `return` is not a keyword, but merely a function return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- We can use this just like we used `getLine`: main'' = do putStrLn "I will echo two lines!" - result <- action + result <- action putStrLn result putStrLn "This was all, folks!" @@ -400,40 +497,60 @@ main'' = do ---------------------------------------------------- --- 9. The Haskell REPL +-- 9. O Haskell REPL (Read Eval Print Loop) ---------------------------------------------------- --- Start the repl by typing `ghci`. --- Now you can type in Haskell code. Any new values --- need to be created with `let`: +{- Digite dhci no seu terminal + para começar o interpretador + lembre-se que para definir + funções e variáveis em haskell + pelo interpretador você precisar + iniciar com `let` +-} -let foo = 5 +Prelude> let foo = 1.4 --- You can see the type of any value with `:t`: +-- Você pode ver o tipo de algo usando `:t`: ->:t foo -foo :: Integer +Prelude> :t foo +foo :: Double +``` --- You can also run any action of type `IO ()` +---------------------------------------------------- +-- 9. Mônadas +---------------------------------------------------- -> sayHello -What is your name? -Friend! -Hello, Friend! -``` -There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: -```haskell -qsort [] = [] -qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater - where lesser = filter (< p) xs - greater = filter (>= p) xs -``` +---------------------------------------------------- +-- 10. Extra +---------------------------------------------------- + +Compilador e Interpretador Haskell + +* [GHC](http://www.haskell.org/ghc/docs/latest/html/users_guide/index.html) +* [GHC/GHCi](http://www.haskell.org/haskellwiki/GHC) + +Instale Haskell [Aqui!](http://www.haskell.org/platform/). + +Aplicações Haskell Muito Interessantes: + +* [Música e Som](http://www.haskell.org/haskellwiki/Applications_and_libraries/Music_and_sound) +* [Haskell SuperCollider Servidor](https://github.com/kaoskorobase/hsc3-server) +* [Haskell SuperCollider Cliente](http://hackage.haskell.org/package/hsc3) +* [Física e Matemática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Mathematics) +* [Jogos](http://www.haskell.org/haskellwiki/Applications_and_libraries/Games) +* [Bio Informática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Bioinformatics) +* [Muitos Outras Aplicações](http://www.haskell.org/haskellwiki/Libraries_and_tools) + +Tutoriais: + +* [Mapeadores](http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Map.html) +* [Aprenda Haskell!](http://haskell.tailorfontela.com.br/chapters) + +Obtenha Também Haskell Wiki Book [Aqui!](https://en.wikibooks.org/wiki/Haskell) -Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). +Leia Sobre As Mônadas [Aqui!](http://www.haskell.org/haskellwiki/Monads) -You can find a much gentler introduction from the excellent -[Learn you a Haskell](http://learnyouahaskell.com/) or -[Real World Haskell](http://book.realworldhaskell.org/). +Livro: Haskell Uma Abordagem Prática - Claudio Cesar de Sá e Márcio Ferreira da Silva -- cgit v1.2.3 From 65b15b280b7c361af7c9baaabf5943a93a3a5931 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 01:54:35 -0200 Subject: Add translate until Haskell::IO Plus some extra references --- pt-br/haskell-pt.html.markdown | 221 ++++++++++++++++++++++------------------- 1 file changed, 119 insertions(+), 102 deletions(-) (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 3d80a44f..f9f9f510 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -227,22 +227,38 @@ let fatorial n = fatorial (n - 1) * n uma lista é `resto` é o resto da lista. -} -mapa mapeador [] = [] +mapa mapeador _ [] = [] mapa mapeador (primeiro : resto) = mapeador primeiro : (mapa mapeador resto) -{- Funções Anônimas são criadas com um `\` (barra invertida) - seguido por seus argumentos! +{- Uma função anônima é uma função sem um nome. + É uma abstração do cálculo lambda: + + \x -> x + 1 + λ.x (x + 1) + + Em Haskell Barra Invertida é um jeito para + se escrever Lambda (λ). Uma ótima pedida + Para entender Haskell e outras linguagens como Lisp + É estudar Cálculo Lambda, é um entendimento matemático + mais apurado. E do ponto de vista computacional é + bastante interessante. Em EXTRAS você encontrará + Links para aprender Cálculo Lambda. -} -mapa (\primeiro -> primeiro + 2) [1..5] -- [3, 4, 5, 6, 7] -{- Usar "fold" (chamado `inject` em algumas outras línguagens) com - uma função anônima. +(\x -> x + 1) 4 -- 5 + - significa E mapeia o primeiro valor - da lista para ser o acumulador. +{- Algumas vezes é mais conveniente usar expressões lambda + do que definir um nome para uma função. Na matemática + Nomes são muito simbólicos. Isso acontece bastante + quando você estiver trabalhando `map` ou `foldl` / `foldr` -} -foldl1 (\acc x -> acc + x) [1..5] -- 15 -foldl1 (\x y -> (x+y)/5) [7..55] -- 13.6875 + +-- Sem usar expressões anônimas ! +listaSomaUm lst = map somaUm' lst where somaUm' x = x + 1 + +-- Usando expressões anônimas ! +listaSomaUm' lst = map (\x -> x + 1) lst ---------------------------------------------------- -- 4. Mais Funções @@ -276,144 +292,142 @@ foo 5 -- 75 {- Concertando precedência: Haskell tem outra função chamada `$`. Isso altera a precedência de computação. Ou seja Haskell computa o que está sendo sinalizado com $ - da esquerda para a direita . You can use `.` and `$` to get rid of a lot - of parentheses: + da esquerda para a direita . Você pode usar `.` e `$` para se livrar + de parentízação desnecessária. -} --- Antes (even (fatorial 3)) -- true --- Depois +-- Usando `.` e `$` even . fatorial $ 3 -- true ---------------------------------------------------- --- 4. More functions +-- 5. Tipos ---------------------------------------------------- -{- Mais Sobre Funções Currificadas: se você não passar - todos os argumentos para uma função. --} - -add a b = a + b -foo = add 10 -- foo is now a function that takes a number and adds 10 to it -foo 5 -- 15 - --- Another way to write the same thing -foo = (+10) -foo 5 -- 15 +-- Haskell é fortemente tipado e tudo tem uma assinatura típica. --- function composition --- the (.) function chains functions together. --- For example, here foo is a function that takes a value. It adds 10 to it, --- multiplies the result of that by 5, and then returns the final value. -foo = (*5) . (+10) +-- Tipos Básicos: +460 :: Integer +"music" :: String +True :: Bool --- (5 + 10) * 5 = 75 -foo 5 -- 75 +{- Funções também tem tipos. + `not` recebe um booleano e retorna um booleano: + not :: Bool -> Bool +-} --- fixing precedence --- Haskell has another function called `$`. This changes the precedence --- so that everything to the left of it gets computed first and then applied --- to everything on the right. You can use `.` and `$` to get rid of a lot --- of parentheses: +{- Aqui temos uma função que recebe dois argumentos + soma :: Integer -> Integer -> Integer +-} --- before -(even (fib 7)) -- true +{- Quando você define um valor em Haskell + uma boa prática de programação é escrever + o TIPO acima dessa mesma. Como segue: +-} --- after -even . fib $ 7 -- true +double :: Integer -> Integer +double x = x * 2 ---------------------------------------------------- --- 5. Type signatures +-- 6. Controle de Fluxo e IF-THEN-ELSE ---------------------------------------------------- --- Haskell has a very strong type system, and everything has a type signature. - --- Some basic types: -5 :: Integer -"hello" :: String -True :: Bool +-- Blocos IF-THEN-ELSE +let valor_alternado = if 144 `mod` 6 == 4 then "acertou" else "errou" -- errou --- Functions have types too. --- `not` takes a boolean and returns a boolean: --- not :: Bool -> Bool +-- É legal identar quando você tem múltiplos branchs para acontecer --- Here's a function that takes two arguments: --- add :: Integer -> Integer -> Integer +let valor_alternado = if 144 `mod` 6 == 4 + then "acertou" + else "errou" --- When you define a value, it's good practice to write its type above it: -double :: Integer -> Integer -double x = x * 2 +-- Blocos CASE ----------------------------------------------------- --- 6. Control Flow and If Statements ----------------------------------------------------- +{- caso seja : + -> mostra_ajuda + -> inicia_programa + <_> -> putStrLn "ExArgumentoInvalido" --- if statements -haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + Onde `_` Significa Qualquer Outra Coisa. +-} --- if statements can be on multiple lines too, indentation is important -haskell = if 1 == 1 - then "awesome" - else "awful" --- case statements: Here's how you could parse command line arguments case args of - "help" -> printHelp - "start" -> startProgram - _ -> putStrLn "bad args" + "ajuda" -> mostra_ajuda + "inicia" -> inicia_programa + _ -> putStrLn "ExArgumentoInvalido" --- Haskell doesn't have loops because it uses recursion instead. --- map applies a function over every element in an array +{- Haskell não funciona na base de loops pois ele é + fortemente baseado em funcões recursivas e cálculo lambda + Use `map` uma função build-in do interpretador + para, por exemplo, mapear uma lista: +-} map (*2) [1..5] -- [2, 4, 6, 8, 10] --- you can make a for function using map -for array func = map func array - --- and then use it +-- Você pode criar um FOR-LOOP usando map +let for array funcao = map funcao array for [0..5] $ \i -> show i --- we could've written that like this too: +-- Ou ainda (Pesquise sobre show em Haskell): for [0..5] show --- You can use foldl or foldr to reduce a list --- foldl + +{- foldl computação é feita esquerda para direita + foldr computação é feita direita para esquerda + + Você pode usar foldl or foldr a fim de reduzir uma lista + fold(l||r) +-} + +-- Fold Left foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- This is the same as -(2 * (2 * (2 * 4 + 1) + 2) + 3) +-- Pensando Recursivamente Esquerda-Direita +(2 * (2 * (2 * 4 + 1) + 2) + 3) -- 43 --- foldl is left-handed, foldr is right- +-- Fold Right foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- This is now the same as +-- Pensando Recursivamente Direita-Esquerda (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- --- 7. Data Types +-- 7. Declaração de Dados ---------------------------------------------------- --- Here's how you make your own data type in Haskell - -data Color = Red | Blue | Green +{- Vamos começar definindo um tipo de + dado que é uma cor rgb então ela + tem valores para vermelho azul e verde + ela é composta desses 3 comprimentos + Vamos usar `data` e `say` que são built-in: + + Haskell pede que você user letra + maiuscula para tipos (types) ou classes (Class) + + Por favor, visite: http://www.haskell.org/haskellwiki/Type + E de uma olhada na fórmula genérica de declaração de dados. +-} --- Now you can use it in a function: +data Cor = Vermelho | Azul | Verde +-- say :: Color -> String -say :: Color -> String -say Red = "You are Red!" -say Blue = "You are Blue!" -say Green = "You are Green!" +let say Vermelho = "Vermelho" +let say Azul = "Azul" +let say Verde = "Verde" --- Your data types can have parameters too: +{- O seu tipo de dados por receber parâmetros também + vamos com um exemplo usando `data` e a Classe `Maybe`. +-} data Maybe a = Nothing | Just a --- These are all of type Maybe -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` +-- Just e Nothing são todos derivadas de Maybe +Just "hello" -- tipo `Maybe String` +Just 1 -- tipo `Maybe Int` +Nothing -- tipo `Maybe a` para algum `a` ---------------------------------------------------- -- 8. Haskell IO @@ -514,18 +528,15 @@ Prelude> let foo = 1.4 Prelude> :t foo foo :: Double -``` ---------------------------------------------------- -- 9. Mônadas ---------------------------------------------------- +``` - ----------------------------------------------------- --- 10. Extra ----------------------------------------------------- +# Extra Compilador e Interpretador Haskell @@ -544,10 +555,16 @@ Aplicações Haskell Muito Interessantes: * [Bio Informática](http://www.haskell.org/haskellwiki/Applications_and_libraries/Bioinformatics) * [Muitos Outras Aplicações](http://www.haskell.org/haskellwiki/Libraries_and_tools) +Comunidade Haskell +* [Musica das Mônadas](http://www.haskell.org/haskellwiki/Music_of_monads) + Tutoriais: * [Mapeadores](http://www.haskell.org/ghc/docs/6.12.2/html/libraries/containers-0.3.0.0/Data-Map.html) * [Aprenda Haskell!](http://haskell.tailorfontela.com.br/chapters) +* [Fundação Teórica da Linguagem Haskell](http://www.haskell.org/haskellwiki/Lambda_calculus) +* [Classe Maybe](http://www.haskell.org/haskellwiki/Maybe) +* [Zvon Referência Haskell](http://www.zvon.org/other/haskell/) Obtenha Também Haskell Wiki Book [Aqui!](https://en.wikibooks.org/wiki/Haskell) -- cgit v1.2.3 From 83ffa7fa41c45ed62900811839700f2b1dbc860f Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 01:57:49 -0200 Subject: Change header contribuitor id to english labels --- pt-br/haskell-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index f9f9f510..62cfd76c 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,6 +1,6 @@ --- -linguagem: haskell -tradutor/contribuidor: +language: haskell +translators/contributors: - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] --- -- cgit v1.2.3 From 3a5dd2320d6f9a669149203a3d4307c1cddfae6e Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 09:24:50 -0200 Subject: Add a complete translation on haskell guide I have translated to brazilian portuguese your Haskell quick guide written by Adit Bhargava plus i have add some new ideas. --- pt-br/haskell-pt.html.markdown | 203 +++++++++++++++++++++++++---------------- 1 file changed, 123 insertions(+), 80 deletions(-) (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 62cfd76c..6b175408 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -402,10 +402,10 @@ foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 tem valores para vermelho azul e verde ela é composta desses 3 comprimentos Vamos usar `data` e `say` que são built-in: - + Haskell pede que você user letra maiuscula para tipos (types) ou classes (Class) - + Por favor, visite: http://www.haskell.org/haskellwiki/Type E de uma olhada na fórmula genérica de declaração de dados. -} @@ -429,86 +429,132 @@ Just "hello" -- tipo `Maybe String` Just 1 -- tipo `Maybe Int` Nothing -- tipo `Maybe a` para algum `a` + ---------------------------------------------------- --- 8. Haskell IO +-- 8. Mônadas ---------------------------------------------------- --- While IO can't be explained fully without explaining monads, --- it is not hard to explain enough to get going. - --- When a Haskell program is executed, the function `main` is --- called. It must return a value of type `IO ()`. For example: - -main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) --- putStrLn has type String -> IO () - --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function --- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the --- output. - -countLines :: String -> String -countLines = show . length . lines - -main' = interact countLines - --- You can think of a value of type `IO ()` as representing a --- sequence of actions for the computer to do, much like a --- computer program written in an imperative language. We can use --- the `do` notation to chain actions together. For example: - -sayHello :: IO () -sayHello = do - putStrLn "What is your name?" - name <- getLine -- this gets a line and gives it the name "name" - putStrLn $ "Hello, " ++ name - --- Exercise: write your own version of `interact` that only reads --- one line of input. - --- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` --- and replace it with: --- main = sayHello - --- Let's understand better how the function `getLine` we just --- used works. Its type is: --- getLine :: IO String --- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` --- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also --- make our own action of type `IO String`: - -action :: IO String -action = do - putStrLn "This is a line. Duh" - input1 <- getLine - input2 <- getLine - -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function - return (input1 ++ "\n" ++ input2) -- return :: String -> IO String - --- We can use this just like we used `getLine`: +{- As mônadas permitem que o programador construa computações + sando os blocos de comando sequenciais, os quais, por sua vez, + podem ter outras sequencias de computações. Para entender melhor + a classe Monads você precisa ler um pouco mais sobre Classes em + Haskell e o polímofirmo ad hoc do Haskell. -main'' = do - putStrLn "I will echo two lines!" - result <- action - putStrLn result - putStrLn "This was all, folks!" + A Classe Mônada padrão em Haskell é a seguinte: +-} + +class Monad m where + (>>=) :: m a -> (a -> m b) -> m b + (>>) :: m a -> m b -> m b + return :: m -> m a + fail :: String -> m a + + -- Definição completa mínima: + -- (>>=), return + + m >> k = m >>= \_ -> k + fail s = error s + +{- Como exemplo, a função le_imprime opera com a função ">=" da + classe mônada, a qual repassa o retorno obtido com a função + getLine para uma função lambda \e qualquer. + + GHC-BASICS + Cria um arquivo chamado le_imprime.hs + compile: ghc --make -c -O Programa_Haskell_Principal.hs + execute: ./Programa_Haskell_Principal +-} --- The type `IO` is an example of a "monad". The way Haskell uses a monad to --- do IO allows it to be a purely functional language. Any function that --- interacts with the outside world (i.e. does IO) gets marked as `IO` in its --- type signature. This lets us reason about what functions are "pure" (don't --- interact with the outside world or modify state) and what functions aren't. +le_imprime :: IO () +le_imprime = getLine >>= \e -> putStrLn e -- le_imprime = getLine >>= putStrLn --- This is a powerful feature, because it's easy to run pure functions --- concurrently; so, concurrency in Haskell is very easy. +{- Mônadas abrem a possibilidade de criar computações + no estilo imperativo dentro de um grande programa funcional + Leis das Mônadas: + + 1. return a >>= k = k a + 2. m >>= return = m + 3. m >>= (\x -> k x >>= h) = (m >>= k) >>= h +-} + +-- O operador >> é chamada então (p -> q, p então q) +let m >> n = m >>= \_ -> n + + +---------------------------------------------------- +-- 9. Haskell Entrada/Saída +---------------------------------------------------- + +{- Quando um programa Haskell é executado a função `main` é + chamada. E ela precisa retornar um valor do tipo IO(). +-} + +module Main where + main :: IO () + main = putStrLn $ "Oi Glasgow!" + +-- Ou simplesmente: + +main = putStrLn $ "Oi Glasgow!" + +{- putStrLn é do tipo String -> IO() + + É o jeito mais fácil de conseguir E/S se você implementar + o seu programa como uma função de String para String. + + A função: + interact :: (String -> String) -> IO () + Joga texto, roda a função nela mesma, e imprime a saída +-} + +module Main where + contadorLinhas = show . length . lines + main = interact contadorLinhas + +-- Use a notação `do` para encadear ações. Por exemplo: + +diga_oi :: IO () + +diga_oi = do + + putStrLn "Qual eh o seu nome?" + name <- getLine + putStrLn $ "Oi, " ++ name + +main = diga_oi + +{- Exercício! Escreva sua própria versão + onde irá ler apenas uma linhas de input. + + Vamos entender melhor como `getLine` funciona? + getLine :: IO String + Pense que o valor do tipo `IO a` representando um + programa de computador que irá gerar um valor do tipo `a` + quando for ele executado. + + Nós podemos guardar e reusar isso apenas apontando `<-`. + Nós podemos também cria nossas próprias ações do tipo `IO String` +-} + +nova_acao :: IO String + +nova_acao = do + putStrLn "Uma string curta o bastante." + entra1 <- getLine + entra2 <- getLine + -- return :: String -> IO String + return (entra1 ++ "\n" ++ entra2) + +{- Nós podemos usar da seguinte maneira + como acabamos de usar `getLine`, exemplo: +-} + +main'' = do + putStrLn "String A" + result <- action + putStrLn result + putStrLn "String B" ---------------------------------------------------- -- 9. O Haskell REPL (Read Eval Print Loop) @@ -528,11 +574,6 @@ Prelude> let foo = 1.4 Prelude> :t foo foo :: Double - ----------------------------------------------------- --- 9. Mônadas ----------------------------------------------------- - ``` @@ -542,6 +583,7 @@ Compilador e Interpretador Haskell * [GHC](http://www.haskell.org/ghc/docs/latest/html/users_guide/index.html) * [GHC/GHCi](http://www.haskell.org/haskellwiki/GHC) +* [Haskell em 5 Passos !!!](http://www.haskell.org/haskellwiki/Haskell_in_5_steps) Instale Haskell [Aqui!](http://www.haskell.org/platform/). @@ -557,6 +599,7 @@ Aplicações Haskell Muito Interessantes: Comunidade Haskell * [Musica das Mônadas](http://www.haskell.org/haskellwiki/Music_of_monads) +* [Entendendo Mônadas](https://en.wikibooks.org/wiki/Haskell/Understanding_monads) Tutoriais: -- cgit v1.2.3 From 67ec5027e56caebe2af2f9a6130c2e9d1803f203 Mon Sep 17 00:00:00 2001 From: Lucas Tonussi Date: Mon, 25 Nov 2013 09:31:18 -0200 Subject: Add the contribuior and translator id's header Just adding a better explained header --- pt-br/haskell-pt.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'pt-br/haskell-pt.html.markdown') diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 6b175408..55f90bd6 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -1,7 +1,11 @@ --- language: haskell -translators/contributors: +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: - ["Lucas Tonussi", "http://www.inf.ufsc.br/~tonussi/"] +lang: pt-br +filename: learnhaskell-pt.hs --- As linguagens funcionais são linguagens de programação com base em avaliação -- cgit v1.2.3