Haskell - foldl $ lambda Set.empty

I think that in this example something is wrong (from the chapter of the book ), or I missed something:

Prelude> let wordSet = foldl (\se -> Data.Set.insert es) Data.Set.empty 

Then:

Prelude> wordSet ["blue", "blue", "red", "blue", "red"]

will not work. Error with error:

Failed to match expected type '()' with actual type '[Char]'

wordSet function wordSet to have no pending parameter?

And it still does not work out why Data.Set.empty is the second foldl parameter, but not the first. And how should we pass stuff to wordSet .

Q: how should it work?

+5
source share
1 answer

this is another case of the terrible restriction of monomorphism

There are several ways around this:

add point

 let wordSet ws = foldl (\se -> Data.Set.insert es) Data.Set.empty ws 

disable restriction

 > :set -XNoMonomorphismRestriction > let wordSet = foldl (\se -> Data.Set.insert es) Data.Set.empty > :t wordSet wordSet :: Ord a => [a] -> containers-0.5.0.0:Data.Set.Base.Set a 

add type signatures inside GHCi (thanks @Zeta)

 let{ wordSet :: Ord e => [e] -> Data.Set.Set e; wordSet = foldl (\se -> Data.Set.insert es) Data.Set.empty} 

use and load the source file (with signature type)

 module WordSet where import Data.Set (Set, insert, empty) wordSet :: (Ord e) => [e] -> Set e wordSet = foldl (\se -> insert es) empty 

use and load the source file (disable restriction)

 {-# LANGUAGE NoMonomorphismRestriction #-} module WordSet where import Data.Set (Set, insert, empty) wordSet = foldl (\se -> insert es) empty 

note: this one is not idiomatic since you must give signatures to the top-level definitions (most likely, the GHC warns you).

+14
source

Source: https://habr.com/ru/post/1201789/


All Articles