binding a partially applied function in Haskell
-
24-06-2021 - |
题
I'm a Haskell newbie, so please excuse me if you find this question trivial:
How would I get GHCi to accept a declaration of this sort: let foo = fmap (*3) . fmap (+10)
?
I tried adding a type declaration to foo (let foo :: [Int] -> [Int] =
etc) to make the functor type explicit but the compiler responds Illegal Signature
.
Thanks!
EDIT - Apparently there are quite a few ways to do this. I picked Tikhon's answer because his was among the first, and also fairly intuitive. Thanks, everyone!
解决方案
You can give the expression (that is, fmap (* 3) . fmap (+ 10)
) a signature rather than giving it to foo
. So:
let foo = fmap (* 3) . fmap (+ 10) :: [Int] -> [Int]
其他提示
To give type signatures in ghci, the best way, not requiring any extensions, is to separate the signature and the binding with a semicolon,
let foo :: Num n => [n] -> [n]; foo = map (*3) . map (+ 10)
The full error reads
Illegal signature in pattern: [Int] -> [Int]
Use -XScopedTypeVariables to permit it
The solution is to run
:set -XScopedTypeVariables
Now you can try running your let foo :: [Int] -> [Int] = fmap (*3) . fmap (+10)
and it will work.
:set -XNoMonomorphismRestriction