haskell - What kind of value do you get when you apply “return” to a value without a constraint? - Stack Overflow

If you apply return to 'a' you get a value of type m Char, belonging to the Monad class: :t r

If you apply return to 'a' you get a value of type m Char, belonging to the Monad class: :t return 'a'return 'a' :: Monad m => m Char. If you apply the resulting value to some other value, say, 42, you get 'a': (return 'a') 42'a'. The same expression with a constraint – (return 'a' :: [Char]) 7 – causes an error. What kind of monadic value, if it is a monadic value, is it? If it is used, what is it used for?

If you apply return to 'a' you get a value of type m Char, belonging to the Monad class: :t return 'a'return 'a' :: Monad m => m Char. If you apply the resulting value to some other value, say, 42, you get 'a': (return 'a') 42'a'. The same expression with a constraint – (return 'a' :: [Char]) 7 – causes an error. What kind of monadic value, if it is a monadic value, is it? If it is used, what is it used for?

Share Improve this question asked Mar 22 at 20:14 SkabSkab 735 bronze badges 1
  • 1 I'm sure there's a better duplicate somewhere, but stackoverflow/questions/69325169/… is very closely related and should be helpful. – amalloy Commented Mar 22 at 20:25
Add a comment  | 

1 Answer 1

Reset to default 3

You make a function call with (return 'a') 42 where (return 'a') is thus the function. This means you use the (->) a monad instance. Indeed [Haskell-src]:

-- | @since base-2.01
instance Functor ((->) r) where
  fmap = (.)

-- | @since base-2.01
instance Applicative ((->) r) where
  pure = const
  f g x = f x (g x)
  liftA2 q f g x = q (f x) (g x)

-- | @since base-2.01
instance Monad ((->) r) where
  f >>= k = \ r -> k (f r) r

So here return = pure = const. Therefore return 'a' is in this context a function that ignores the parameter, and returns 'a', so (return 'a') 42 will return 'a'.

what is it used for?

To combine functions. For example:

myFunc :: Int -> Int
myFunc = do
  a <- (*2)
  b <- (3+)
  return (a+b)

Is a function that takes a value x, then calculates a = (x*2) and b = (3+x), and finally returns a+b, so it maps x to 2*x+x+3.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744304832a4567677.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信