Article image
Alyson Silva
Alyson Silva14/08/2022 11:52
Compartilhe

Trabalhando com listas em Haskell

    Criando listas:

    -- -----------------
    -- lista vazia    
    
    []
        
    1 : []               = [1]
    1 : 2 : [3]          = [1,2,3]
    1 : 2 : [3] ++ [4]   = [1,2,3,4]
    
    -- -----------------
    -- compreensão de lista 
    -- [x1..xn]  and  [f x | x <- [x1..xn]]
    
    [1..5]    = [1,2,3,4,5]
    [1..]     = [1,2,3,4,5,..]    -- lista infinita!
    
    [ x+2 | x <- [1..4] ] = [3,4,5,6]
    
    -- ------------------
    -- ( let in )
    
    let f x = x + 2 in [ f x | x <- [1..4] ] = [3,4,5,6]
    
    -- ------------------
    -- ( where )
    
    ( 
      [ f x | x <- [1..4] ]  
        where
        f x = (x + 2)
    )                       = [3,4,5,6]
    
    -- ------------------
    -- Funções recursivas com listas (patter matching)
    -- função (f) recebe (::) lista de inteiros ([Int]) devolve (->) lista de inteiros ([Int]) 
    
    f :: [Int] -> [Int]
    f []     = []            -- caso receber lista vazia ([]) retorna (=) lista vazia ([])
    f (x:xs) = (x+2) : f xs  -- tail recurssion
    
    f [1..4] = [3,4,5,6]     -- (x:xs) = [1..4]   then   x = 1   and   xs = [2..4]
      
    

    Uma simples introdução a Haskell.

    Uma Linguagem de Programação Puramente Funcional.

    Compartilhe
    Comentários (0)