DEV Community

Cover image for Hangman in PureScript
Riccardo Odone
Riccardo Odone

Posted on • Updated on • Originally published at

Hangman in PureScript

You can keep reading here or jump to my blog to get the full experience, including the wonderful pink, blue and white palette.

Hangman in PureScript

An example run

Insert word to guess
> hello
Try to guess
> hol
> hello
You won!
Enter fullscreen mode Exit fullscreen mode

The code

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.ReadLine as RL
import Data.String.Yarn (fromChars, toChars) as S
import Data.List.Lazy as L
import Data.String (length) as S

mask :: String -> String -> String
mask word guess =
  let as = S.toChars word :: L.List Char
      bs = S.toChars guess :: L.List Char
      bs' = bs <> L.replicate (L.length as - L.length bs) '-'
      zipper a b = if a == b then a else '-'
      S.fromChars $ L.zipWith zipper as bs'

main :: Effect Unit
main = do
    interface <- RL.createConsoleInterface RL.noCompletion
        lineHandler word guess =
            case word of
                 "" -> do
                    log $ S.fromChars $ L.take (S.length guess) (L.repeat '-')
                    log "Try to guess"
                    RL.setLineHandler interface $ lineHandler guess
                    RL.setPrompt "> " 2 interface
                    RL.prompt interface
                 _ ->
                    if word == guess then do
                        RL.close interface
                        log "You won!"
                    else do
                        log $ mask word guess
                        RL.setPrompt "> " 2 interface
                        RL.prompt interface
    RL.setLineHandler interface $ lineHandler ""
    log "Insert word to guess"
    RL.setPrompt "> " 2 interface
    RL.prompt interface
Enter fullscreen mode Exit fullscreen mode

Get the latest content via email from me personally. Reply with your thoughts. Let's learn from each other. Subscribe to my PinkLetter!

Top comments (2)

glebec profile image
Gabriel Lebec

Heh – I guess brevity is the soul of wit. ;-)

riccardoodone profile image
Riccardo Odone

Hehe, I can elaborate if anything's obscure!