r/haskelltil • • Mar 19 '15

tools :sprint in GHCi lets you view thunks

34 Upvotes

From Parallel and Concurrent Programming in Haskell:

> let xs = map (+1) [1..10] :: [Int]

> :sprint xs
xs = _

> seq xs ()
()

> :sprint xs
_ : _

> length xs
10

> :sprint xs
[_,_,_,_,_,_,_,_,_,_]

> sum xs
65

> :sprint xs
[2,3,4,5,6,7,8,9,10,11]

r/haskelltil • • Jan 06 '21

TIL list has many Monad structures

Thumbnail hackage.haskell.org
32 Upvotes

r/haskelltil • • Apr 11 '16

code Coyoneda is just the Free Functor

28 Upvotes

I just learned it from John de Goes, in his (Scala) presentation on Free Applicatives. Other than this offhand remark, he doesn't explain what Coyoneda is or what it's useful for, for that purpose I recommend Loop School's Coyoneda video.

I've heard multiple times before that Coyoneda f is a Functor even when f isn't, but the information didn't stick, because it seemed like one of many funky properties of a complicated-looking definition. The Loop School video made Coyoneda a lot more understandable, but the video didn't make it look important enough for me to remember it as more than a curious contraption. As a result, I never used it, and I have to look up its definition each time I hear the name.

This time I'm quite certain I won't forget, because Coyoneda now fits neatly in a mental shelf next to FreeApplicative and FreeMonad. As a Free Functor, its defining property is that it adds just enough structure to turn any f into a Functor. So of course Coyoneda f is a Functor even when f isn't! And by now I've seen enough free structures that its implementation is obvious, so I won't have to lookup its definition anymore. Compare:

data FreeFunctor f a where
  FMap :: (s -> a) -> f s -> FreeFunctor f a

instance Functor (FreeFunctor f) where
  fmap f (FMap s_to_a fs) = FMap s_to_b fs
    where s_to_b = fmap f s_to_a


-- Note that it is *not*
--   Ap :: FreeApplicative f (s -> a) -> FreeApplicative f s -> FreeApplicative f a
--   (<*>) = Ap
-- because that would violate "free_f <*> Pure a = Pure ($ a) <*> free_f". Instead,
-- we normalize such expressions by pushing Pure as far left as possible.
data FreeApplicative f a where
  Pure :: a -> FreeApplicative f a
  Ap   :: FreeApplicative f (s -> a) -> f s -> FreeApplicative f a

instance Functor (FreeApplicative f) where
  fmap f (Pure a)            = Pure (f a)
  fmap f (Ap free_s_to_a fs) = Ap free_s_to_b fs
    where free_s_to_b = fmap (fmap f) free_s_to_a

instance Applicative (FreeApplicative f) where
  pure = Pure
  Pure f            <*> free_a = fmap f free_a
  Ap free_s_to_f fs <*> free_a = Ap free_s_to_b fs
    where free_s_to_a_to_b = free_s_to_f
          free_a_to_s_to_b = fmap flip free_s_to_a_to_b
          free_s_to_b = free_a_to_s_to_b <*> free_a


-- As before, it is *not*
--   Bind :: FreeMonad f s -> (s -> FreeMonad f a) -> FreeMonad f a
--   (>>=) = Bind
-- because that would violate "Return a >>= f = f a". Instead, we normalize
-- such expressions by pushing Return as far right as possible.
-- 
-- Variation: Control.Monad.Free assumes f is a functor and pre-applies
-- "fmap s_to_free_a fs", resulting in
--   Bind :: f (FreeMonad f a) -> FreeMonad f a
data FreeMonad f a where
  Return :: a -> FreeMonad f a
  Bind   :: f s -> (s -> FreeMonad f a) -> FreeMonad f a

instance Functor (FreeMonad f) where
  fmap f (Return a)            = Return (f a)
  fmap f (Bind fs s_to_free_a) = Bind fs s_to_free_b
    where s_to_free_b = fmap (fmap f) s_to_free_a

instance Applicative (FreeMonad f) where
  pure = Return
  Return f            <*> free_a = fmap f free_a
  Bind fs s_to_free_f <*> free_a = Bind fs s_to_free_b
    where s_to_free_b = fmap (<*> free_a) s_to_free_f

instance Monad (FreeMonad f) where
  return = Return
  Return a            >>= a_to_free_b = a_to_free_b a
  Bind fs s_to_free_a >>= a_to_free_b = Bind fs s_to_free_b
    where s_to_free_b = fmap (>>= a_to_free_b) s_to_free_a

r/haskelltil • • Sep 02 '15

etc Write “module Main (main) where” instead of “module Main where” to get warnings about unused functions

27 Upvotes

This is obvious in hindsight, but still.

No warnings:

module Main where

main = putStrLn "hello world"

f x = x*x

A warning about Defined but not used: ‘f’:

module Main (main) where

main = putStrLn "hello world"

f x = x*x

r/haskelltil • • Mar 22 '15

etc You generally can't pass polymorphic arguments to functions (but “$” is special, so special)

27 Upvotes

For instance, id is polymorphic: its type is forall a. a -> a. Can you write a function which uses it? I mean, not some specialised version (when you e.g. write id True and id gets specialised to Bool -> Bool), but the fully general id?

g f = (f True, f 'x')

Not so easily:

    Couldn't match expected type ‘Bool’ with actual type ‘Char’
    In the first argument of ‘f’, namely ‘'x'’
    In the expression: f 'x'
    In the expression: (f True, f 'x')

Okay, you can if you add a type signature (GHC doesn't infer higher-ranked types, you have to add type signatures):

g :: (forall a. a -> a) -> (Bool, Char)
g f = (f True, f 'x')

And you can pass id to it:

> g id
(True, 'x')

You can even add other functions to the mix:

> g $ id
(True, 'x')

But it all breaks when you try to use anything but $:

> g . id $ id

<interactive>:
    Couldn't match type ‘a0 -> a0’ with ‘forall a. a -> a’
    Expected type: (a0 -> a0) -> (Bool, t)
      Actual type: (forall a. a -> a) -> (Bool, t)
    In the first argument of ‘(.)’, namely ‘g’
    In the expression: g . id

Even if you define your own $, it won't work the same way $ does:

> let (?) = ($)

> :t (?)
(?) :: (a -> b) -> a -> b
> :t ($)
($) :: (a -> b) -> a -> b

> g ? id

<interactive>:
    Couldn't match type ‘a0 -> a0’ with ‘forall a. a -> a’
    Expected type: (a0 -> a0) -> (Bool, t)
      Actual type: (forall a. a -> a) -> (Bool, t)
    In the first argument of ‘(?)’, namely ‘g’
In the expression: g ? id

The reason for all this magic is that $ has a special typing rule in GHC specifically to let it apply functions to polymorphic values; see this question for details.


r/haskelltil • • Jul 25 '15

tools Expand type synonyms in GHCi with “:kind!” and “:i”

26 Upvotes

If you have a simple synonym like String, you can expand it with :i:

> :i String
type String = [Char] 	-- Defined in ‘GHC.Base’

However, :i won't do substitution for things like Lens' String Char. For that you can use :kind!:

> :kind! Lens' String Char
Lens' String Char :: *
= Functor f => (Char -> f Char) -> String -> f String

If you have type variables in your type, you would have to use forall, otherwise you would see “not in scope” errors:

> :kind! Lens (a, x) (b, x) a b

<interactive>:1:7: Not in scope: type variable ‘a’
...

But with forall it works:

> :kind! forall a x b. Lens (a, x) (b, x) a b
forall a x b. Lens (a, x) (b, x) a b :: *
= Functor f => (a -> f b) -> (a, x) -> f (b, x)

r/haskelltil • • Aug 09 '15

language Arguments can be operators, e.g.: f (+.) a b = a +. b

25 Upvotes

The parentheses trick for operators works in other contexts, too. You can bind parameters using operator-like names if you surround them with parentheses:

let f (%) x y = x % y
in  f (*) 1 2

-- ... desugars to:
(\(%) x y -> x % y) (*) 1 2

-- ... reduces to:
1 * 2

Source


r/haskelltil • • Oct 22 '18

Easy way to replace default Prelude with the alternative one using mixins

24 Upvotes

Decided to put this useful hint here just in case somebody is interested

cabal-version:       2.2
name:                prelude-example
version:             0.0.0.0

library
  exposed-modules:     Example
  build-depends:       base >= 4.10 && < 4.13
                     , relude ^>= 0.5.0

  mixins:              base hiding (Prelude)
                     , relude (Relude as Prelude)

  default-language:    Haskell2010

r/haskelltil • • Jun 09 '15

extension -XLambdaCase makes "\case" sugar for "\x -> case x of"

24 Upvotes

This is an RTFM situation, but there's just so much damn M. :P

Straight from the docs:


The -XLambdaCase flag enables expressions of the form

\case { p1 -> e1; ...; pN -> eN }

which is equivalent to

\freshName -> case freshName of { p1 -> e1; ...; pN -> eN }

Note that \case starts a layout, so you can write

\case
  p1 -> e1
  ...
  pN -> eN

r/haskelltil • • Apr 22 '15

language As-patterns can be chained: { let x@y@z = 1 in (x,y,z) } == (1,1,1)

24 Upvotes

r/haskelltil • • Sep 25 '17

tools GHC 8.2.1 and newer allow you to error on specific warnings using `-Werror=foo`

23 Upvotes

There was an /r/haskellquestions post and I was about to say that there was no way yet, but then I looked at the trac page and the relevant ticket learned something new and awesome.


r/haskelltil • • Apr 27 '15

language You can use f X{} = ... instead of f (X _ _ _) = ...

23 Upvotes

This is useful if you don't care about the number of arguments to the constructor.


r/haskelltil • • Mar 27 '15

tools GHCi binds the last evaluated expression to "it".

23 Upvotes

Similar to Python's '_', GHCi binds the value of the last evaluated expression to 'it'.

Prelude > 1 + 1
2
Prelude > it
2
Prelude > getLine
abc
"abc"
Prelude > :t it
it :: String

r/haskelltil • • Mar 19 '15

thing “readMaybe” is a version of “read” which lets you check for failure

22 Upvotes

It's been in Text.Read since base-4.6.

> readMaybe "8" :: Maybe Int
Just 8

> readMaybe "foo" :: Maybe Int
Nothing

And if you want to see the exception text, there's readEither:

> readEither "foo" :: Either String Int
Left "Prelude.read: no parse"

r/haskelltil • • Nov 30 '18

printAllThreads

21 Upvotes

If you compile this file with ghc -debug Main.hs:

module Main where
 
foreign import ccall safe "printAllThreads" printAllThreads :: IO ()
 
main :: IO ()
main = printAllThreads

it will give the following output:

all threads:
threads on capability 0:
other threads:
	thread    1 @ 0x4200105388 is blocked on an external call (TSO_DIRTY)

r/haskelltil • • Jul 18 '15

thing Starting from base-4.8 (GHC 7.10), bifunctors are in base – you can stop importing Control.Arrow just to get “first” and “second”

21 Upvotes

Well, now you have to import Data.Bifunctor to get first and second, but I think bifunctors are nicer than arrows and so we all should switch anyway.

By the way, if you never needed first and second and don't know what they do:

> first (+1) (1, "hello")
(2, "hello")

> second reverse (1, "hello")
(1, "olleh")

r/haskelltil • • Mar 18 '15

language “data S a = S !a” is standard Haskell 98 and doesn't need -XBangPatterns

21 Upvotes

(Thanks to this comment.)

I thought strictness declarations for data types needed the BangPatterns extension, but turns out they don't. BangPatterns is only needed for... erm, ri-ight... patterns.

Links:


r/haskelltil • • Mar 08 '21

Entering : by itself in GHCi will run the most recent command you've used

Thumbnail self.haskell
19 Upvotes

r/haskelltil • • Oct 04 '19

Servant has underdocumented *required* QueryParams.

19 Upvotes

QueryParam' '[Required] "name" Text

Then your function is a instead of Maybe a.


r/haskelltil • • Mar 24 '17

TIL: unfoldr

19 Upvotes

For some reason I didn't know it. It allows building a list recursively.

unfoldr :: (b -> Maybe (a,b)) -> b -> [a]

A cute implementation of Eratosthenes' sieve using it:

import Data.List

divides :: Int -> Int -> Bool
divides a b = b `rem` a == 0

sieve :: [Int] -> Maybe (Int, [Int])
sieve [] = Nothing
sieve (x:xs) = Just (x, filter (not . divides x) xs)

primes :: Int -> [Int]
primes n = unfoldr sieve [2 .. n]

r/haskelltil • • Jun 27 '16

gotcha undefined isn't always a valid dummy implementation

19 Upvotes
{-# LANGUAGE RankNTypes #-}

This compiles:

useIdentityTwice :: (forall a. a -> a)
                 -> (Int, Char) -> (Int, Char)
useIdentityTwice _ = undefined

This does not:

-- Cannot instantiate unification variable
-- with a type involving foralls
-- GHC doesn't yet support impredicative polymorphism
useIdentityTwice' :: (forall a. a -> a)
                  -> (Int, Char) -> (Int, Char)
useIdentityTwice' = undefined

r/haskelltil • • Jul 25 '15

code A handy function for debugging in Parsec by what printing a parser is currently seeing.

19 Upvotes

Since Parsec is quite procedural in how it consumes characters, it is easy to mis-parse input by eating too many or too few characters. In those cases having a function like this that outputs the current state of the input stream is useful:

seeNext :: Int -> ParsecT String u Identity ()
seeNext n = do
  s <- getParserState
  let out = take n (stateInput s)
  println out

Here's a full program that shows usage:

import Text.Parsec
import Text.Parsec.Prim
import Debug.Trace
import Data.Functor.Identity

println msg = trace (show msg) $ return ()

seeNext :: Int -> ParsecT String u Identity ()
seeNext n = do
  s <- getParserState
  let out = take n (stateInput s)
  println out

betweenBraces = char '{' >> manyTill (seeNext 10 >> anyChar) (char '}')

test = parseTest betweenBraces "{12345}"

{-
> test
"12345}"
"2345}"
"345}"
"45}"
"5}"
"12345"
-}

r/haskelltil • • Mar 19 '15

language Functions (not just operators) can have fixity and precedence, too

19 Upvotes

You can set fixity for operators, like this:

infixr 8 ^

This line means that ^ (power) would be applied right-to-left, and that its precedence is 8:

> 2^2^3
256

> (2^2)^3
64

However, since functions can be used as operators (when you surround them with backticks), they are allowed to have fixity and precedence just as well. For instance, for elem the declaration looks like this:

infix 4 `elem`

+ has higher precedence than elem, but lower than mod, which is the reason why both these expressions work as intended:

> x`mod`7 + 1            -- (x`mod`7) + 1

> x+1 `elem` primes      -- (x+1) `elem` primes

r/haskelltil • • Jul 28 '21

Declarations can precede signatures

18 Upvotes

From https://twitter.com/mattoflambda/status/1417962508367826947

-- >> main
-- 10
main = do
 let x = 10
     x :: Int

 pr x where

 pr = print
 pr :: Int -> IO ()