Haskell

Z Varhoo
Přejít na: navigace, hledání

Příklady

Načtení souboru a vypsání dat do vstupu s informací o číslu řádku

import IO
showFile f1 = do
  h1 <- openFile f1 ReadMode
  c1 <- hGetContents h1
  putStr $ unlines $ [ (show a) ++ ": " ++ b | (a,b) <- (zip [0..(length ( lines c1 ))] (lines c1) ) ]


Vytvoření binárního stromu

data Tree a = Lf 
         | Nd a (Tree a) (Tree a)
         deriving (Eq)
createTree x = Nd x Lf Lf
addTree (Nd c l r) x 
  |  x < c = if l == Lf 
        then (Nd c (createTree x) r)
        else Nd c (addTree l x) r
  | x >= c = if r == Lf 
        then Nd c l (createTree x) 
        else Nd c l (addTree r x)
array2tree [] = error "empty array"
array2tree (x:xs) = rr (createTree x) xs
  where rr tree [] = tree
        rr tree (x:xs) = rr (addTree tree x) xs

Procházení binárního stromu

inOdr Lf = []
inOdr (Nd x l r) = (inOdr l) ++ (x:inOdr r)
preOdr Lf = [] 
preOdr (Nd x l r) = (x:(preOdr l)) ++ (preOdr r)
postOdr Lf = [] 
postOdr (Nd x l r) = (postOdr l) ++ (postOdr r) ++ [x]