I guess there is something wrong in this example (from the book's chapter) or I miss something:
Prelude> let wordSet = foldl (\s e -> Data.Set.insert e s) Data.Set.empty
Then:
Prelude> wordSet ["blue", "blue", "red", "blue", "red"]
will not work. It will fail with an error:
Couldn't match expected type '()' with actual type `[Char]'
Seems wordSet
function has no any expecting parameter to pass?
And still don't get why Data.Set.empty
is the second param of foldl
but not first. And how are we supposed to pass stuff into the wordSet
.
Q: how it is supposed to work?
this is another case of the dreaded monomorphism restriction
There are several ways to circumvent this:
let wordSet ws = foldl (\s e -> Data.Set.insert e s) Data.Set.empty ws
> :set -XNoMonomorphismRestriction
> let wordSet = foldl (\s e -> Data.Set.insert e s) Data.Set.empty
> :t wordSet
wordSet :: Ord a => [a] -> containers-0.5.0.0:Data.Set.Base.Set a
let{ wordSet :: Ord e => [e] -> Data.Set.Set e; wordSet = foldl (\s e -> Data.Set.insert e s) Data.Set.empty}
module WordSet where
import Data.Set (Set, insert, empty)
wordSet :: (Ord e) => [e] -> Set e
wordSet = foldl (\s e -> insert e s) empty
{-# LANGUAGE NoMonomorphismRestriction #-}
module WordSet where
import Data.Set (Set, insert, empty)
wordSet = foldl (\s e -> insert e s) empty
please note: this one is not-idiomatic as you should give signatures to your top-level definitions (GHC will most likely warn you).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With