Skip to content

Instantly share code, notes, and snippets.

@aricneto
Last active April 27, 2019 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aricneto/cd93f834fe69261790583aaa5f743e07 to your computer and use it in GitHub Desktop.
Save aricneto/cd93f834fe69261790583aaa5f743e07 to your computer and use it in GitHub Desktop.
-- ariovaldo capuano neto (acn2)
-- (questao 1)
meio :: String -> Int -> Int -> String
meio _ _ 0 = ""
meio "" _ _ = ""
meio str x y
| (x < 0) || (y < 0) = ""
| (length str) >= x = str!!(x-1) : (meio (tail str) x (y-1))
| otherwise = ""
-- (fim questao 1)
-- ==++==++==
-- (questao 2)
localizar :: String -> String -> Int
localizar "" _ = 0
localizar srch st = localizar' srch srch st 1
localizar' :: String -> String -> String -> Int -> Int
localizar' origSch [] _ idx = (idx - (length origSch))
localizar' _ _ [] _ = 0
localizar' origSch (s:sch) (w:wrd) idx
| s == w = localizar' origSch sch wrd (idx + 1)
| otherwise = localizar' origSch origSch wrd (idx + 1)
-- (fim da questao 2)
-- ==++==++==
-- (questao 3)
data Comando = ParaFrente Int | ParaTras Int | Escreva Char
deriving (Show, Eq)
-- escreve o char na posicao especificada da fita e retorna a nova fita
escreve :: String -> Char -> Int -> String
escreve fita c cursor = escreve' "" fita c cursor
escreve' :: String -> String -> Char -> Int -> String
escreve' _ [] _ _ = ""
escreve' pre (a:pos) c cursor
| cursor == 1 = pre ++ c : pos
| otherwise = escreve' (pre ++ a:[]) pos c (cursor - 1)
-- auxiliar de operacao de 3-upla
tfst :: (a,b,c) -> a
tfst (a, _, _) = a
tsnd :: (a,b,c) -> b
tsnd (_, b, _) = b
ttrd :: (a,b,c) -> c
ttrd (_, _, c) = c
-- opera a fita e retorna uma 3-upla com a posicao e caractere da cabeca final, e a fita final
-- estado cabeca comm
operaFita :: String -> Int -> [Comando] -> (Int, Char, String)
operaFita fita h [] = (h, fita!!(h-1), fita)
operaFita fita h (comm:comms) =
case comm of
(ParaFrente x) -> operaFita fita (h+x) comms
(ParaTras x) -> operaFita fita (h-x) comms
(Escreva c) -> operaFita (escreve fita c h) h comms
-- (questao 3.1)
posicaoFinal :: String -> [Comando] -> Int
posicaoFinal str comms = tfst (operaFita str 1 comms)
-- (fim questao 3.1)
-- (questao 3.2)
interprete :: String -> [Comando] -> Char
interprete str comms = tsnd (operaFita str 1 comms)
-- (fim questao 3.2)
-- (questao 3.3)
estadoFinal :: String -> [Comando] -> String
estadoFinal str comms = ttrd (operaFita str 1 comms)
-- (fim questao 3.3)
-- (fim questao 3)
-- ==++==++==
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment