EMZETT.
Login

Kurz: Die mein-projekt.cabal-Datei:

Teil des Kurses Haskell

Kapitel 9 von 9 im Kurs Haskell (Abschnitt „Nachschlagen“). Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Die Werkzeuge

WerkzeugZweck
GHCder Compiler (ghc -O2 Main.hs)
GHCiinteraktive Umgebung zum Ausprobieren
CabalBuild-System und Paketmanager (cabal build, cabal run, cabal test)
StackAlternative zu Cabal mit festen Paketmengen (Stackage)
GHCupInstallationsprogramm für GHC, Cabal, Stack, HLS
HLSHaskell Language Server (Editor-Unterstützung)
Hackage / HooglePaketarchiv / Funktionssuche nach Typ (hoogle.haskell.org)
HLint, Ormolu/FourmoluStil-Tipps und Formatierer
cabal init --interactive         # neues Projekt
cabal build
cabal run mein-projekt
cabal repl                       # GHCi mit Projekt
cabal test
cabal install --lib containers

Die mein-projekt.cabal-Datei:

cabal-version:      3.0
name:               mein-projekt
version:            0.1.0.0
 
executable mein-projekt
    main-is:          Main.hs
    hs-source-dirs:   app
    build-depends:    base ^>=4.18, containers, text
    default-language: Haskell2010
    ghc-options:      -Wall

GHCi: wichtige Befehle

ghci> :t map                  -- Typ anzeigen
map :: (a -> b) -> [a] -> [b]
ghci> :i Maybe                -- Informationen zu einem Namen
ghci> :l Datei.hs             -- laden
ghci> :r                      -- neu laden
ghci> :k Maybe                -- Kind (Typ von Typen)
ghci> :q

Hoogle: Suche nach der Typsignatur, z. B. [a] -> Int findet length.

Häufig genutzte Erweiterungen

{-# LANGUAGE OverloadedStrings #-}   -- String-Literale als Text
{-# LANGUAGE LambdaCase #-}          -- \case Muster
{-# LANGUAGE TupleSections #-}       -- (,x)
{-# LANGUAGE ScopedTypeVariables #-} -- Typannotationen in Mustern
{-# LANGUAGE RecordWildCards #-}     -- Person{..}
{-# LANGUAGE DeriveFunctor #-}       -- deriving Functor
{-# LANGUAGE LambdaCase, TupleSections, RecordWildCards #-}
 
data Konfig = Konfig { host :: String, port :: Int }
 
beschreibe :: Konfig -> String
beschreibe Konfig {..} = host ++ ":" ++ show port
 
status :: Int -> String
status = \case
  200 -> "OK"
  404 -> "Nicht gefunden"
  _ -> "anderes"
 
main :: IO ()
main = do
  putStrLn (beschreibe (Konfig "localhost" 8080))
  print (map status [200, 404, 500])
  print (map (,True) [1, 2])

Ausgabe:

localhost:8080
["OK","Nicht gefunden","anderes"]
[(1,True),(2,True)]

Typklassen- und Funktionsübersicht

ThemaWichtige Namen
Listenmap filter foldr foldl' zip zipWith take drop takeWhile span concat concatMap
Zahlen+ - * / div mod quot rem ^ ** sqrt fromIntegral round floor ceiling
Textshow read words unwords lines unlines ++ concat
Maybe/EitherJust Nothing maybe fromMaybe Left Right either
Funktionenid const flip . $ <$> <*> >>= uncurry curry
IOputStrLn print getLine readFile writeFile mapM_ forM_ when
Vergleich== /= < > compare max min

Häufige Fehlermeldungen

MeldungUrsache
Couldn't match expected type ‘Int’ with actual type ‘[Char]’falscher Typ: Signatur und Ausdruck passen nicht
No instance for (Show a) arising from ...Show a => in der Signatur fehlt
Variable not in scopeTippfehler oder fehlender import
Non-exhaustive patterns in function fnicht alle Fälle abgedeckt (-Wall warnt)
parse error on inputEinrückung/Syntax; where, let ausrichten
Ambiguous type variableTyp nicht eindeutig: (read x :: Int)
Occurs check: cannot construct the infinite typeFunktion wird falsch angewendet
Couldn't match type ‘IO’ with ‘[]’do-Block mit gemischten Monaden

Tipp

Lies Typfehler von unten nach oben und prüfe die Signaturen. Der Compiler weiß fast immer, wo es hakt. Mit _ im Code (“typed hole”) zeigt GHC dir den erwarteten Typ.

Weiterlernen

  • Learn You a Haskell for Great Good! (learnyouahaskell.com) und Haskell Programming from First Principles
  • Real World Haskell, Parallel and Concurrent Programming in Haskell
  • Übungen: Exercism (Haskell-Track), Advent of Code, 99 Haskell Problems
  • Wiki dieser Seite: Artikel zu funktionaler Programmierung

Merke

  • Typen führen: erst die Signatur, dann die Definition
  • map/filter/fold statt Schleifen, Pattern Matching statt if-Ketten
  • Maybe/Either statt null und Exceptions; IO am Rand des Programms
  • Cabal/Stack, Hoogle und -Wall sind deine Werkzeuge

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Maps, Sets, Text und Module

Alle Kapitel: Haskell im Überblick