Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - foldl $ lambda Set.empty

Tags:

lambda

haskell

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?

like image 768
ses Avatar asked Sep 04 '14 03:09

ses


1 Answers

this is another case of the dreaded monomorphism restriction

There are several ways to circumvent this:

add the point

let wordSet ws = foldl (\s e -> Data.Set.insert e s) Data.Set.empty ws

disable the restriction

> :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

add type-signatures inside GHCi (thank you @Zeta)

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

use and load a source file (with type-signatures)

module WordSet where

import Data.Set (Set, insert, empty)

wordSet :: (Ord e) => [e] -> Set e
wordSet = foldl (\s e -> insert e s) empty 

use and load a source file (disable the restriction)

{-# 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).

like image 197
Random Dev Avatar answered Nov 12 '22 07:11

Random Dev