Skip to content

Instantly share code, notes, and snippets.

@lipemorais
Created February 18, 2016 14:31
Show Gist options
  • Save lipemorais/00c7dbedba0785743767 to your computer and use it in GitHub Desktop.
Save lipemorais/00c7dbedba0785743767 to your computer and use it in GitHub Desktop.
Programação Funcional no Haskell
import Prelude hiding (elem, map)
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem x (y:ys)
| x == y = True
| otherwise = elem x ys
factorial :: Int -> Int
factorial 1 = 1
factorial x = x * factorial(x-1)
factorial' :: Int -> Int
factorial' x = foldr (*) 1 [1..x]
factorial'' :: Int -> Int
factorial'' x = if x == 1
then 1
else x * factorial'' (x-1)
map :: (a -> a) -> [a] -> [a]
map _ [] = []
map f (x:xs) = f x : map f xs
-- Quicksort
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = quicksort small ++ [x] ++ quicksort large
where small = [y | y <- xs, y <= x]
large = [y | y <- xs, y > x]
-- Reverse Words
reverseWords :: String -> String
reverseWords = unwords . map reverse . words
-- Cesar Cipher
import Data.Char
encode :: Int -> String -> String
encode shift msg =
let ords = map ord msg
shifted = map (+ shift) ords
in map chr shifted
encode' :: Int -> String -> String
encode' shift msg = map (chr ( (+ shift) (ord))) msg
decode :: Int -> String -> String
decode shift msg =
let ords = map ord msg
shifted = map (+(negate shift)) ords
in map chr shifted
decode' :: Int -> String -> String
decode' shift msg = map (chr . (+(negate shift)) . ord) msg
decode'' :: Int -> String -> String
decode'' shift msg = encode (negate shift) msg
-- Python
-- chr(ord('a')+3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment