I have the following Haskell expression:
a = getLine >>= putStrLn . filter isDigit >> a
I am having trouble understanding how the above expression works. I know the >>=
function takes a monadic value and a function (that takes a normal value and returns a monadic value), and returns a monadic value.
I know that getLine
and putStrLn
have the following type declarations:
getLine :: IO String
putStrLn :: String -> IO ()
So the following part of expression:
a = getLine >>= putStrLn . filter isDigit
Would return an IO ()
. However, the function >>
takes a first monadic value and a second monadic value and returns the second monadic value.
Given the original expression, the first argument passed to >>
would be of type IO String
. The second argument is a
.
My question is, what is the type of a
, and how does the above expression work to continually take user input and print only the numeric part of the input back to the screen? Any insights are appreciated.
a :: IO t
. Yes, it's polymorphic. An infinite computation never returns anything, so it can be any type. – AJFa=a
(an infinite recursion), the type would bea :: forall b. b
, i.e.a
could be of any typeb
. Since we have insteada = ioAction >> a
, we forceb
to be of the formIO t
, butt
can be anything. So we geta :: forall t. IO t
. It is still an infinite recursion, except that the IO action is run at every recursive call. In a sense, this works since>>
won't evaluate its second argument/action before having executed its first argument/action. – chia = (getLine >>= (putStrLn . filter isDigit)) >> a
. (both>>
and>>=
areinfixl 1
). – Will Ness>>
would be of typeIO String
". What do you believe the first argument passed to>>
is? Why do you believe it to have typeIO String
? (That is not the correct type for the first argument, so if you explain your thinking, we may help you spot an error in it.) – Daniel Wagner