Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The usage of let in Haskell

I have this code in Haskell.

import Data.List

main = do
    putStrLn $ "\nVerify if Exists in a String"
    let wordlist = ["monad", "monoid", "Galois", "ghc", "SPJ"]
    let tweet = "This is an example tweet talking about SPJ interviewing with Galois"
    print $ map (flip isInfixOf tweet) wordlist

Without the let, I have this error message: 10_things.hs:16:14: parse error on input ‘=’.

This is another code that works fine.

import Data.List

wordlist = ["monad", "monoid", "Galois", "ghc", "SPJ"]
tweet = "This is an example tweet talking about SPJ interviewing with Galois"      
main = do
    putStrLn $ "\nVerify if Exists in a String"
    print $ map (flip isInfixOf tweet) wordlist

In this case, I have error parse error (possibly incorrect indentation or mismatched brackets) with let. My question is when and when not to use let in Haskell?

like image 691
prosseek Avatar asked Dec 03 '22 17:12

prosseek


1 Answers

Declarations/equations need to be inside either a let or a where block. The reason you don't need let at the top level of a module, is that it counts as a where block all by itself, started by its module declaration. A module which doesn't contain an explicit module header gets an implicit

module Main (main) where

at the beginning.

By the way, an indented let block can contain more than one declaration: you don't need the second let in your code as long as the equations line up vertically.

like image 184
Ørjan Johansen Avatar answered Jan 03 '23 05:01

Ørjan Johansen