Haskell Overlapping/Incoherent Instances

后端 未结 2 1340
一个人的身影
一个人的身影 2021-02-20 01:11

I know this is code is a bit silly, but can someone explain why this isList [42] returns True whereas isList2 [42] prints False

2条回答
  •  眼角桃花
    2021-02-20 01:35

    The following code does the trick without requiring IncoherentInstances:

    {-# LANGUAGE FlexibleInstances #-}
    {-# LANGUAGE OverlappingInstances #-}
    
    class IsList a where
      isList :: a -> Bool
    
    instance IsList a where
      isList x = False
    
    instance IsList [a] where
      isList x = True
    
    isList2 :: (IsList a) => a -> Bool
    isList2 = isList
    
    main = do
      print (isList (42 :: Int))
      print (isList [42 :: Int])
      print (isList2 (42 :: Int))
      print (isList2 [42 :: Int])
    

    I'd recommend not using IncoherentInstances, it seems to cause a lot of trouble, as you can silently call different overloads depending on context quite easily.

提交回复
热议问题