r/haskelltil • • May 14 '15

gotcha You cannot pattern match against variable values.

1 Upvotes

Consider this example:

myValue1 = 1 :: Int
myValue2 = 2 :: Int

myFunc :: Int -> Bool
myFunc myValue1 = True
myFunc myValue2 = False

If you load the above program in ghci, you get following output:

myFunc.hs:5:1: Warning:
   Pattern match(es) are overlapped
   In an equation for ‘myFunc’: myFunc myValue2 = ...
Ok, modules loaded: Main.

ghci generates a warning but does not give any errors. If you now call myFunc myValue2 you get:

*Main> myFunc myValue2
True

One way to get the desired result would be to use guards:

myFunc :: Int -> Bool
myFunc x
  | x == myValue1 = True
  | x == myValue2 = False

Note that we might not always be lucky enough to get a compiler warning in such cases. Here is an example:

myFunc :: Maybe Int -> Int
myFunc v = case v of
                Just myValue -> myValue
                _            -> myValue + 1
                  where myValue = 0

This loads in ghci without any warnings.


r/haskelltil • • Nov 19 '20

Question About Pattern Matching Style

Thumbnail self.haskellquestions
0 Upvotes

r/haskelltil • • Apr 25 '15

tools You can use “x <- someAction” in GHCi

8 Upvotes
> s <- readFile "/usr/share/dict/words"

> length (words s)
119095

Basically, what you can do after main = do, you can do in GHCi (but you can do more than that, of course – import modules, define types and classes and instances, etc.).


r/haskelltil • • Sep 27 '19

Do notation syntax is probably a rip-off from Perl

5 Upvotes

While looking at nofib's runstdtest.pl today, I had to squint really hard to see that that script isn't actually generating Haskell code but uses proper Perl syntax.

Note how that's exactly the style of do-notation (explicit braces + semicolons) SPJ prefers.


r/haskelltil • • Mar 02 '20

GHC has a --show-options flag

7 Upvotes
$ ghc-8.8.3 --show-options
-package-db
-clear-package-db
-no-global-package-db
-no-user-package-db
-global-package-db
-user-package-db
-package-conf
-no-user-package-conf
-package-name
-this-package-key
-this-unit-id
-package
-plugin-package-id
-plugin-package
-package-id
-hide-package
-hide-all-packages
-hide-all-plugin-packages
-package-env
-ignore-package
-syslib
-distrust-all-packages
-trust
-distrust
-n
-cpp
-F
-#include
-v
-j
-instantiated-with
-this-component-id
-H
-Rghc-timing
-prof
-eventlog
-smp
-debug
-threaded
-ticky
-static
-dynamic
-rdynamic
-relative-dynlib-paths
-copy-libs-when-linking
-pie
-no-pie
-pgmlo
-pgmlc
-pgmi
-pgmL
-pgmP
-pgmF
-pgmc
-pgms
-pgma
-pgml
-pgmdll
-pgmwindres
-pgmlibtool
-pgmar
-pgmranlib
-optlo
-optlc
-opti
-optL
-optP
-optF
-optc
-opta
-optl
-optwindres
-split-objs
-split-sections
-dep-suffix
-dep-makefile
-include-pkg-deps
-exclude-module
-no-link
-shared
-staticlib
-dynload
-dylib-install-name
-L
-l
-framework-path
-framework
-odir
-o
-dyno
-ohi
-osuf
-dynosuf
-hcsuf
-hisuf
-hiesuf
-dynhisuf
-hidir
-hiedir
-tmpdir
-stubdir
-dumpdir
-outputdir
-ddump-file-prefix
-dynamic-too
-keep-hc-file
-keep-hc-files
-keep-hscpp-file
-keep-hscpp-files
-keep-s-file
-keep-s-files
-keep-llvm-file
-keep-llvm-files
-keep-tmp-files
-keep-hi-file
-no-keep-hi-file
-keep-hi-files
-no-keep-hi-files
-keep-o-file
-no-keep-o-file
-keep-o-files
-no-keep-o-files
-no-auto-link-packages
-no-hs-main
-fno-state-hack
-fno-opt-coercion
-with-rtsopts
-rtsopts
-rtsopts=all
-rtsopts=some
-rtsopts=none
-rtsopts=ignore
-rtsopts=ignoreAll
-no-rtsopts
-no-rtsopts-suggestions
-dhex-word-literals
-ghcversion-file
-main-is
-haddock
-haddock-opts
-hpcdir
-ticky-allocd
-ticky-LNE
-ticky-dyn-thunk
-recomp
-no-recomp
-fmax-errors
-fno-max-errors
-freverse-errors
-fno-reverse-errors
-D
-U
-I
-i
-dppr-user-length
-dppr-cols
-fdiagnostics-color=auto
-fdiagnostics-color=always
-fdiagnostics-color=never
-dsuppress-all
-dstg-stats
-ddump-cmm
-ddump-cmm-from-stg
-ddump-cmm-raw
-ddump-cmm-verbose
-ddump-cmm-cfg
-ddump-cmm-cbe
-ddump-cmm-switch
-ddump-cmm-proc
-ddump-cmm-sp
-ddump-cmm-sink
-ddump-cmm-caf
-ddump-cmm-procmap
-ddump-cmm-split
-ddump-cmm-info
-ddump-cmm-cps
-ddump-cfg-weights
-ddump-core-stats
-ddump-asm
-ddump-asm-native
-ddump-asm-liveness
-ddump-asm-regalloc
-ddump-asm-conflicts
-ddump-asm-regalloc-stages
-ddump-asm-stats
-ddump-asm-expanded
-ddump-llvm
-ddump-deriv
-ddump-ds
-ddump-ds-preopt
-ddump-foreign
-ddump-inlinings
-ddump-rule-firings
-ddump-rule-rewrites
-ddump-simpl-trace
-ddump-occur-anal
-ddump-parsed
-ddump-parsed-ast
-ddump-rn
-ddump-rn-ast
-ddump-simpl
-ddump-simpl-iterations
-ddump-spec
-ddump-prep
-ddump-stg
-ddump-call-arity
-ddump-exitify
-ddump-stranal
-ddump-str-signatures
-ddump-tc
-ddump-tc-ast
-ddump-types
-ddump-rules
-ddump-cse
-ddump-worker-wrapper
-ddump-rn-trace
-ddump-shape
-ddump-if-trace
-ddump-cs-trace
-ddump-tc-trace
-ddump-ec-trace
-ddump-vt-trace
-ddump-splices
-dth-dec-file
-ddump-rn-stats
-ddump-opt-cmm
-ddump-simpl-stats
-ddump-bcos
-dsource-stats
-dverbose-core2core
-dverbose-stg2stg
-ddump-hi
-ddump-minimal-imports
-ddump-hpc
-ddump-ticked
-ddump-mod-cycles
-ddump-mod-map
-ddump-timings
-ddump-view-pattern-commoning
-ddump-to-file
-ddump-hi-diffs
-ddump-rtti
-dcore-lint
-dstg-lint
-dcmm-lint
-dasm-lint
-dannot-lint
-dshow-passes
-dfaststring-stats
-dno-llvm-mangler
-fast-llvm
-ddump-debug
-ddump-json
-dppr-debug
-ddebug-output
-dno-debug-output
-msse
-msse2
-msse3
-msse4
-msse4.2
-mbmi
-mbmi2
-mavx
-mavx2
-mavx512cd
-mavx512er
-mavx512f
-mavx512pf
-W
-Werror
-Wwarn
-Wnot
-w
-Weverything
-Wno-everything
-Wall
-Wno-all
-Wextra
-Wno-extra
-Wdefault
-Wno-default
-Wcompat
-Wno-compat
-fplugin-opt
-fplugin
-fclear-plugins
-ffrontend-opt
-Onot
-O
-fmax-relevant-binds
-fno-max-relevant-binds
-fmax-valid-hole-fits
-fno-max-valid-hole-fits
-fmax-refinement-hole-fits
-fno-max-refinement-hole-fits
-frefinement-level-hole-fits
-fno-refinement-level-hole-fits
-fllvm-pass-vectors-in-regs
-fmax-uncovered-patterns
-fsimplifier-phases
-fmax-simplifier-iterations
-fmax-pmcheck-iterations
-fsimpl-tick-factor
-fspec-constr-threshold
-fno-spec-constr-threshold
-fspec-constr-count
-fno-spec-constr-count
-fspec-constr-recursive
-fliberate-case-threshold
-fno-liberate-case-threshold
-drule-check
-dinline-check
-freduction-depth
-fconstraint-solver-iterations
-fcontext-stack
-ftype-function-depth
-fstrictness-before
-ffloat-lam-args
-ffloat-all-lams
-fstg-lift-lams-rec-args
-fstg-lift-lams-rec-args-any
-fstg-lift-lams-non-rec-args
-fstg-lift-lams-non-rec-args-any
-fstg-lift-lams-known
-fno-stg-lift-lams-known
-fproc-alignment
-fblock-layout-weights
-fhistory-size
-funfolding-creation-threshold
-funfolding-use-threshold
-funfolding-fun-discount
-funfolding-dict-discount
-funfolding-keeness-factor
-fmax-worker-args
-fmax-inline-alloc-size
-fmax-inline-memcpy-insns
-fmax-inline-memset-insns
-dinitial-unique
-dunique-increment
-auto-all
-no-auto-all
-auto
-no-auto
-caf-all
-no-caf-all
-fprof-auto
-fprof-auto-top
-fprof-auto-exported
-fprof-auto-calls
-fno-prof-auto
-fasm
-fvia-c
-fvia-C
-fllvm
-fno-code
-fbyte-code
-fobject-code
-fglasgow-exts
-fno-glasgow-exts
-Wunused-binds
-Wno-unused-binds
-fpackage-trust
-fno-safe-infer
-fno-safe-haskell
-fPIC
-fno-PIC
-fPIE
-fno-PIE
-g
-dppr-case-as-let
-dppr-ticks
-dsuppress-ticks
-dsuppress-stg-free-vars
-dsuppress-stg-exts
-dsuppress-coercions
-dsuppress-idinfo
-dsuppress-unfoldings
-dsuppress-module-prefixes
-dsuppress-timestamps
-dsuppress-type-applications
-dsuppress-type-signatures
-dsuppress-uniques
-dsuppress-var-kinds
-dno-ppr-case-as-let
-dno-ppr-ticks
-dno-suppress-ticks
-dno-suppress-stg-free-vars
-dno-suppress-stg-exts
-dno-suppress-coercions
-dno-suppress-idinfo
-dno-suppress-unfoldings
-dno-suppress-module-prefixes
-dno-suppress-timestamps
-dno-suppress-type-applications
-dno-suppress-type-signatures
-dno-suppress-uniques
-dno-suppress-var-kinds
-fasm-shortcutting
-fbuilding-cabal-package
-fcall-arity
-fexitification
-fcase-merge
-fcase-folding
-fcmm-elim-common-blocks
-fcmm-sink
-fcse
-fstg-cse
-fstg-lift-lams
-fcpr-anal
-fdefer-type-errors
-fdefer-typed-holes
-fdefer-out-of-scope-variables
-fdiagnostics-show-caret
-fdicts-cheap
-fdicts-strict
-fdmd-tx-dict-sel
-fdo-eta-reduction
-fdo-lambda-eta-expansion
-feager-blackholing
-fembed-manifest
-fenable-rewrite-rules
-ferror-spans
-fexcess-precision
-fexpose-all-unfoldings
-fexternal-dynamic-refs
-fexternal-interpreter
-fflat-cache
-ffloat-in
-fforce-recomp
-fignore-optim-changes
-fignore-hpc-changes
-ffull-laziness
-ffun-to-thunk
-fgen-manifest
-fghci-history
-fghci-leak-check
-fvalidate-ide-info
-fghci-sandbox
-fhelpful-errors
-fhpc
-fignore-asserts
-fignore-interface-pragmas
-firrefutable-tuples
-fkill-absence
-fkill-one-shot
-flate-dmd-anal
-flate-specialise
-fliberate-case
-floopification
-fblock-layout-cfg
-fblock-layout-weightless
-fomit-interface-pragmas
-fomit-yields
-foptimal-applicative-do
-fpedantic-bottoms
-fpre-inlining
-fprint-explicit-foralls
-fprint-explicit-kinds
-fprint-explicit-coercions
-fprint-explicit-runtime-reps
-fprint-equality-relations
-fprint-unicode-syntax
-fprint-expanded-synonyms
-fprint-potential-instances
-fprint-typechecker-elaboration
-fprof-cafs
-fprof-count-entries
-fregs-graph
-fregs-iterative
-frewrite-rules
-fshared-implib
-fspec-constr
-fspec-constr-keen
-fspecialise
-fspecialize
-fspecialise-aggressively
-fspecialize-aggressively
-fcross-module-specialise
-fcross-module-specialize
-fstatic-argument-transformation
-fstrictness
-fuse-rpaths
-fwrite-interface
-fwrite-ide-info
-funbox-small-strict-fields
-funbox-strict-fields
-fversion-macros
-fworker-wrapper
-fsolve-constant-dicts
-fcatch-bottoms
-falignment-sanitisation
-fnum-constant-folding
-fshow-warning-groups
-fhide-source-paths
-fshow-loaded-modules
-fwhole-archive-hs-libs
-fkeep-cafs
-fshow-hole-constraints
-fshow-valid-substitutions
-fshow-valid-hole-fits
-fsort-valid-hole-fits
-fsort-by-size-hole-fits
-fsort-by-subsumption-hole-fits
-fabstract-refinement-hole-fits
-fshow-hole-matches-of-hole-fits
-fshow-provenance-of-hole-fits
-fshow-type-of-hole-fits
-fshow-type-app-of-hole-fits
-fshow-type-app-vars-of-hole-fits
-fshow-docs-of-hole-fits
-funclutter-valid-hole-fits
-fno-asm-shortcutting
-fno-building-cabal-package
-fno-call-arity
-fno-exitification
-fno-case-merge
-fno-case-folding
-fno-cmm-elim-common-blocks
-fno-cmm-sink
-fno-cse
-fno-stg-cse
-fno-stg-lift-lams
-fno-cpr-anal
-fno-defer-type-errors
-fno-defer-typed-holes
-fno-defer-out-of-scope-variables
-fno-diagnostics-show-caret
-fno-dicts-cheap
-fno-dicts-strict
-fno-dmd-tx-dict-sel
-fno-do-eta-reduction
-fno-do-lambda-eta-expansion
-fno-eager-blackholing
-fno-embed-manifest
-fno-enable-rewrite-rules
-fno-error-spans
-fno-excess-precision
-fno-expose-all-unfoldings
-fno-external-dynamic-refs
-fno-external-interpreter
-fno-flat-cache
-fno-float-in
-fno-force-recomp
-fno-ignore-optim-changes
-fno-ignore-hpc-changes
-fno-full-laziness
-fno-fun-to-thunk
-fno-gen-manifest
-fno-ghci-history
-fno-ghci-leak-check
-fno-validate-ide-info
-fno-ghci-sandbox
-fno-helpful-errors
-fno-hpc
-fno-ignore-asserts
-fno-ignore-interface-pragmas
-fno-irrefutable-tuples
-fno-kill-absence
-fno-kill-one-shot
-fno-late-dmd-anal
-fno-late-specialise
-fno-liberate-case
-fno-loopification
-fno-block-layout-cfg
-fno-block-layout-weightless
-fno-omit-interface-pragmas
-fno-omit-yields
-fno-optimal-applicative-do
-fno-pedantic-bottoms
-fno-pre-inlining
-fno-print-explicit-foralls
-fno-print-explicit-kinds
-fno-print-explicit-coercions
-fno-print-explicit-runtime-reps
-fno-print-equality-relations
-fno-print-unicode-syntax
-fno-print-expanded-synonyms
-fno-print-potential-instances
-fno-print-typechecker-elaboration
-fno-prof-cafs
-fno-prof-count-entries
-fno-regs-graph
-fno-regs-iterative
-fno-rewrite-rules
-fno-shared-implib
-fno-spec-constr
-fno-spec-constr-keen
-fno-specialise
-fno-specialize
-fno-specialise-aggressively
-fno-specialize-aggressively
-fno-cross-module-specialise
-fno-cross-module-specialize
-fno-static-argument-transformation
-fno-strictness
-fno-use-rpaths
-fno-write-interface
-fno-write-ide-info
-fno-unbox-small-strict-fields
-fno-unbox-strict-fields
-fno-version-macros
-fno-worker-wrapper
-fno-solve-constant-dicts
-fno-catch-bottoms
-fno-alignment-sanitisation
-fno-num-constant-folding
-fno-show-warning-groups
-fno-hide-source-paths
-fno-show-loaded-modules
-fno-whole-archive-hs-libs
-fno-keep-cafs
-fno-show-hole-constraints
-fno-show-valid-substitutions
-fno-show-valid-hole-fits
-fno-sort-valid-hole-fits
-fno-sort-by-size-hole-fits
-fno-sort-by-subsumption-hole-fits
-fno-abstract-refinement-hole-fits
-fno-show-hole-matches-of-hole-fits
-fno-show-provenance-of-hole-fits
-fno-show-type-of-hole-fits
-fno-show-type-app-of-hole-fits
-fno-show-type-app-vars-of-hole-fits
-fno-show-docs-of-hole-fits
-fno-unclutter-valid-hole-fits
-Walternative-layout-rule-transitional
-Wauto-orphans
-Wcpp-undef
-Wunbanged-strict-patterns
-Wdeferred-type-errors
-Wdeferred-out-of-scope-variables
-Wdeprecations
-Wdeprecated-flags
-Wderiving-typeable
-Wdodgy-exports
-Wdodgy-foreign-imports
-Wdodgy-imports
-Wempty-enumerations
-Wduplicate-constraints
-Wredundant-constraints
-Wduplicate-exports
-Whi-shadowing
-Winaccessible-code
-Wimplicit-prelude
-Wimplicit-kind-vars
-Wincomplete-patterns
-Wincomplete-record-updates
-Wincomplete-uni-patterns
-Winline-rule-shadowing
-Widentities
-Wmissing-fields
-Wmissing-import-lists
-Wmissing-export-lists
-Wmissing-local-sigs
-Wmissing-local-signatures
-Wmissing-methods
-Wmissing-monadfail-instances
-Wsemigroup
-Wmissing-signatures
-Wmissing-exported-sigs
-Wmissing-exported-signatures
-Wmonomorphism-restriction
-Wname-shadowing
-Wnoncanonical-monad-instances
-Wnoncanonical-monadfail-instances
-Wnoncanonical-monoid-instances
-Worphans
-Woverflowed-literals
-Woverlapping-patterns
-Wmissed-specialisations
-Wmissed-specializations
-Wall-missed-specialisations
-Wall-missed-specializations
-Wsafe
-Wtrustworthy-safe
-Wtabs
-Wtype-defaults
-Wtyped-holes
-Wpartial-type-signatures
-Wunrecognised-pragmas
-Wunsafe
-Wunsupported-calling-conventions
-Wunsupported-llvm-version
-Wmissed-extra-shared-lib
-Wunticked-promoted-constructors
-Wunused-do-bind
-Wunused-foralls
-Wunused-imports
-Wunused-local-binds
-Wunused-matches
-Wunused-pattern-binds
-Wunused-top-binds
-Wunused-type-patterns
-Wwarnings-deprecations
-Wwrong-do-bind
-Wmissing-pattern-synonym-signatures
-Wmissing-deriving-strategies
-Wsimplifiable-class-constraints
-Wmissing-home-modules
-Wunrecognised-warning-flags
-Wstar-binder
-Wstar-is-type
-Wmissing-space-after-bang
-Wpartial-fields
-Wno-alternative-layout-rule-transitional
-Wno-auto-orphans
-Wno-cpp-undef
-Wno-unbanged-strict-patterns
-Wno-deferred-type-errors
-Wno-deferred-out-of-scope-variables
-Wno-deprecations
-Wno-deprecated-flags
-Wno-deriving-typeable
-Wno-dodgy-exports
-Wno-dodgy-foreign-imports
-Wno-dodgy-imports
-Wno-empty-enumerations
-Wno-duplicate-constraints
-Wno-redundant-constraints
-Wno-duplicate-exports
-Wno-hi-shadowing
-Wno-inaccessible-code
-Wno-implicit-prelude
-Wno-implicit-kind-vars
-Wno-incomplete-patterns
-Wno-incomplete-record-updates
-Wno-incomplete-uni-patterns
-Wno-inline-rule-shadowing
-Wno-identities
-Wno-missing-fields
-Wno-missing-import-lists
-Wno-missing-export-lists
-Wno-missing-local-sigs
-Wno-missing-local-signatures
-Wno-missing-methods
-Wno-missing-monadfail-instances
-Wno-semigroup
-Wno-missing-signatures
-Wno-missing-exported-sigs
-Wno-missing-exported-signatures
-Wno-monomorphism-restriction
-Wno-name-shadowing
-Wno-noncanonical-monad-instances
-Wno-noncanonical-monadfail-instances
-Wno-noncanonical-monoid-instances
-Wno-orphans
-Wno-overflowed-literals
-Wno-overlapping-patterns
-Wno-missed-specialisations
-Wno-missed-specializations
-Wno-all-missed-specialisations
-Wno-all-missed-specializations
-Wno-safe
-Wno-trustworthy-safe
-Wno-tabs
-Wno-type-defaults
-Wno-typed-holes
-Wno-partial-type-signatures
-Wno-unrecognised-pragmas
-Wno-unsafe
-Wno-unsupported-calling-conventions
-Wno-unsupported-llvm-version
-Wno-missed-extra-shared-lib
-Wno-unticked-promoted-constructors
-Wno-unused-do-bind
-Wno-unused-foralls
-Wno-unused-imports
-Wno-unused-local-binds
-Wno-unused-matches
-Wno-unused-pattern-binds
-Wno-unused-top-binds
-Wno-unused-type-patterns
-Wno-warnings-deprecations
-Wno-wrong-do-bind
-Wno-missing-pattern-synonym-signatures
-Wno-missing-deriving-strategies
-Wno-simplifiable-class-constraints
-Wno-missing-home-modules
-Wno-unrecognised-warning-flags
-Wno-star-binder
-Wno-star-is-type
-Wno-missing-space-after-bang
-Wno-partial-fields
-Werror=alternative-layout-rule-transitional
-Werror=auto-orphans
-Werror=cpp-undef
-Werror=unbanged-strict-patterns
-Werror=deferred-type-errors
-Werror=deferred-out-of-scope-variables
-Werror=deprecations
-Werror=deprecated-flags
-Werror=deriving-typeable
-Werror=dodgy-exports
-Werror=dodgy-foreign-imports
-Werror=dodgy-imports
-Werror=empty-enumerations
-Werror=duplicate-constraints
-Werror=redundant-constraints
-Werror=duplicate-exports
-Werror=hi-shadowing
-Werror=inaccessible-code
-Werror=implicit-prelude
-Werror=implicit-kind-vars
-Werror=incomplete-patterns
-Werror=incomplete-record-updates
-Werror=incomplete-uni-patterns
-Werror=inline-rule-shadowing
-Werror=identities
-Werror=missing-fields
-Werror=missing-import-lists
-Werror=missing-export-lists
-Werror=missing-local-sigs
-Werror=missing-local-signatures
-Werror=missing-methods
-Werror=missing-monadfail-instances
-Werror=semigroup
-Werror=missing-signatures
-Werror=missing-exported-sigs
-Werror=missing-exported-signatures
-Werror=monomorphism-restriction
-Werror=name-shadowing
-Werror=noncanonical-monad-instances
-Werror=noncanonical-monadfail-instances
-Werror=noncanonical-monoid-instances
-Werror=orphans
-Werror=overflowed-literals
-Werror=overlapping-patterns
-Werror=missed-specialisations
-Werror=missed-specializations
-Werror=all-missed-specialisations
-Werror=all-missed-specializations
-Werror=safe
-Werror=trustworthy-safe
-Werror=tabs
-Werror=type-defaults
-Werror=typed-holes
-Werror=partial-type-signatures
-Werror=unrecognised-pragmas
-Werror=unsafe
-Werror=unsupported-calling-conventions
-Werror=unsupported-llvm-version
-Werror=missed-extra-shared-lib
-Werror=unticked-promoted-constructors
-Werror=unused-do-bind
-Werror=unused-foralls
-Werror=unused-imports
-Werror=unused-local-binds
-Werror=unused-matches
-Werror=unused-pattern-binds
-Werror=unused-top-binds
-Werror=unused-type-patterns
-Werror=warnings-deprecations
-Werror=wrong-do-bind
-Werror=missing-pattern-synonym-signatures
-Werror=missing-deriving-strategies
-Werror=simplifiable-class-constraints
-Werror=missing-home-modules
-Werror=unrecognised-warning-flags
-Werror=star-binder
-Werror=star-is-type
-Werror=missing-space-after-bang
-Werror=partial-fields
-Wwarn=alternative-layout-rule-transitional
-Wwarn=auto-orphans
-Wwarn=cpp-undef
-Wwarn=unbanged-strict-patterns
-Wwarn=deferred-type-errors
-Wwarn=deferred-out-of-scope-variables
-Wwarn=deprecations
-Wwarn=deprecated-flags
-Wwarn=deriving-typeable
-Wwarn=dodgy-exports
-Wwarn=dodgy-foreign-imports
-Wwarn=dodgy-imports
-Wwarn=empty-enumerations
-Wwarn=duplicate-constraints
-Wwarn=redundant-constraints
-Wwarn=duplicate-exports
-Wwarn=hi-shadowing
-Wwarn=inaccessible-code
-Wwarn=implicit-prelude
-Wwarn=implicit-kind-vars
-Wwarn=incomplete-patterns
-Wwarn=incomplete-record-updates
-Wwarn=incomplete-uni-patterns
-Wwarn=inline-rule-shadowing
-Wwarn=identities
-Wwarn=missing-fields
-Wwarn=missing-import-lists
-Wwarn=missing-export-lists
-Wwarn=missing-local-sigs
-Wwarn=missing-local-signatures
-Wwarn=missing-methods
-Wwarn=missing-monadfail-instances
-Wwarn=semigroup
-Wwarn=missing-signatures
-Wwarn=missing-exported-sigs
-Wwarn=missing-exported-signatures
-Wwarn=monomorphism-restriction
-Wwarn=name-shadowing
-Wwarn=noncanonical-monad-instances
-Wwarn=noncanonical-monadfail-instances
-Wwarn=noncanonical-monoid-instances
-Wwarn=orphans
-Wwarn=overflowed-literals
-Wwarn=overlapping-patterns
-Wwarn=missed-specialisations
-Wwarn=missed-specializations
-Wwarn=all-missed-specialisations
-Wwarn=all-missed-specializations
-Wwarn=safe
-Wwarn=trustworthy-safe
-Wwarn=tabs
-Wwarn=type-defaults
-Wwarn=typed-holes
-Wwarn=partial-type-signatures
-Wwarn=unrecognised-pragmas
-Wwarn=unsafe
-Wwarn=unsupported-calling-conventions
-Wwarn=unsupported-llvm-version
-Wwarn=missed-extra-shared-lib
-Wwarn=unticked-promoted-constructors
-Wwarn=unused-do-bind
-Wwarn=unused-foralls
-Wwarn=unused-imports
-Wwarn=unused-local-binds
-Wwarn=unused-matches
-Wwarn=unused-pattern-binds
-Wwarn=unused-top-binds
-Wwarn=unused-type-patterns
-Wwarn=warnings-deprecations
-Wwarn=wrong-do-bind
-Wwarn=missing-pattern-synonym-signatures
-Wwarn=missing-deriving-strategies
-Wwarn=simplifiable-class-constraints
-Wwarn=missing-home-modules
-Wwarn=unrecognised-warning-flags
-Wwarn=star-binder
-Wwarn=star-is-type
-Wwarn=missing-space-after-bang
-Wwarn=partial-fields
-Wno-error=alternative-layout-rule-transitional
-Wno-error=auto-orphans
-Wno-error=cpp-undef
-Wno-error=unbanged-strict-patterns
-Wno-error=deferred-type-errors
-Wno-error=deferred-out-of-scope-variables
-Wno-error=deprecations
-Wno-error=deprecated-flags
-Wno-error=deriving-typeable
-Wno-error=dodgy-exports
-Wno-error=dodgy-foreign-imports
-Wno-error=dodgy-imports
-Wno-error=empty-enumerations
-Wno-error=duplicate-constraints
-Wno-error=redundant-constraints
-Wno-error=duplicate-exports
-Wno-error=hi-shadowing
-Wno-error=inaccessible-code
-Wno-error=implicit-prelude
-Wno-error=implicit-kind-vars
-Wno-error=incomplete-patterns
-Wno-error=incomplete-record-updates
-Wno-error=incomplete-uni-patterns
-Wno-error=inline-rule-shadowing
-Wno-error=identities
-Wno-error=missing-fields
-Wno-error=missing-import-lists
-Wno-error=missing-export-lists
-Wno-error=missing-local-sigs
-Wno-error=missing-local-signatures
-Wno-error=missing-methods
-Wno-error=missing-monadfail-instances
-Wno-error=semigroup
-Wno-error=missing-signatures
-Wno-error=missing-exported-sigs
-Wno-error=missing-exported-signatures
-Wno-error=monomorphism-restriction
-Wno-error=name-shadowing
-Wno-error=noncanonical-monad-instances
-Wno-error=noncanonical-monadfail-instances
-Wno-error=noncanonical-monoid-instances
-Wno-error=orphans
-Wno-error=overflowed-literals
-Wno-error=overlapping-patterns
-Wno-error=missed-specialisations
-Wno-error=missed-specializations
-Wno-error=all-missed-specialisations
-Wno-error=all-missed-specializations
-Wno-error=safe
-Wno-error=trustworthy-safe
-Wno-error=tabs
-Wno-error=type-defaults
-Wno-error=typed-holes
-Wno-error=partial-type-signatures
-Wno-error=unrecognised-pragmas
-Wno-error=unsafe
-Wno-error=unsupported-calling-conventions
-Wno-error=unsupported-llvm-version
-Wno-error=missed-extra-shared-lib
-Wno-error=unticked-promoted-constructors
-Wno-error=unused-do-bind
-Wno-error=unused-foralls
-Wno-error=unused-imports
-Wno-error=unused-local-binds
-Wno-error=unused-matches
-Wno-error=unused-pattern-binds
-Wno-error=unused-top-binds
-Wno-error=unused-type-patterns
-Wno-error=warnings-deprecations
-Wno-error=wrong-do-bind
-Wno-error=missing-pattern-synonym-signatures
-Wno-error=missing-deriving-strategies
-Wno-error=simplifiable-class-constraints
-Wno-error=missing-home-modules
-Wno-error=unrecognised-warning-flags
-Wno-error=star-binder
-Wno-error=star-is-type
-Wno-error=missing-space-after-bang
-Wno-error=partial-fields
-Werror=compat
-Wno-error=compat
-Wwarn=compat
-fth
-ffi
-fffi
-farrows
-fimplicit-prelude
-fbang-patterns
-fmonomorphism-restriction
-fmono-pat-binds
-fextended-default-rules
-fimplicit-params
-fscoped-type-variables
-fallow-overlapping-instances
-fallow-undecidable-instances
-fallow-incoherent-instances
-fno-th
-fno-fi
-fno-ffi
-fno-arrows
-fno-implicit-prelude
-fno-bang-patterns
-fno-monomorphism-restriction
-fno-mono-pat-binds
-fno-extended-default-rules
-fno-implicit-params
-fno-scoped-type-variables
-fno-allow-overlapping-instances
-fno-allow-undecidable-instances
-fno-allow-incoherent-instances
-XAllowAmbiguousTypes
-XAlternativeLayoutRule
-XAlternativeLayoutRuleTransitional
-XArrows
-XAutoDeriveTypeable
-XBangPatterns
-XBinaryLiterals
-XCApiFFI
-XCPP
-XConstrainedClassMethods
-XConstraintKinds
-XDataKinds
-XDatatypeContexts
-XDefaultSignatures
-XDeriveAnyClass
-XDeriveDataTypeable
-XDeriveFoldable
-XDeriveFunctor
-XDeriveGeneric
-XDeriveLift
-XDeriveTraversable
-XDerivingStrategies
-XDerivingVia
-XDisambiguateRecordFields
-XDoAndIfThenElse
-XBlockArguments
-XDoRec
-XDuplicateRecordFields
-XEmptyCase
-XEmptyDataDecls
-XEmptyDataDeriving
-XExistentialQuantification
-XExplicitForAll
-XExplicitNamespaces
-XExtendedDefaultRules
-XFlexibleContexts
-XFlexibleInstances
-XForeignFunctionInterface
-XFunctionalDependencies
-XGADTSyntax
-XGADTs
-XGHCForeignImportPrim
-XGeneralizedNewtypeDeriving
-XGeneralisedNewtypeDeriving
-XImplicitParams
-XImplicitPrelude
-XImpredicativeTypes
-XIncoherentInstances
-XTypeFamilyDependencies
-XInstanceSigs
-XApplicativeDo
-XInterruptibleFFI
-XJavaScriptFFI
-XKindSignatures
-XLambdaCase
-XLiberalTypeSynonyms
-XMagicHash
-XMonadComprehensions
-XMonadFailDesugaring
-XMonoLocalBinds
-XMonoPatBinds
-XMonomorphismRestriction
-XMultiParamTypeClasses
-XMultiWayIf
-XNumericUnderscores
-XNPlusKPatterns
-XNamedFieldPuns
-XNamedWildCards
-XNegativeLiterals
-XHexFloatLiterals
-XNondecreasingIndentation
-XNullaryTypeClasses
-XNumDecimals
-XOverlappingInstances
-XOverloadedLabels
-XOverloadedLists
-XOverloadedStrings
-XPackageImports
-XParallelArrays
-XParallelListComp
-XPartialTypeSignatures
-XPatternGuards
-XPatternSignatures
-XPatternSynonyms
-XPolyKinds
-XPolymorphicComponents
-XQuantifiedConstraints
-XPostfixOperators
-XQuasiQuotes
-XRank2Types
-XRankNTypes
-XRebindableSyntax
-XRecordPuns
-XRecordWildCards
-XRecursiveDo
-XRelaxedLayout
-XRelaxedPolyRec
-XRoleAnnotations
-XScopedTypeVariables
-XStandaloneDeriving
-XStarIsType
-XStaticPointers
-XStrict
-XStrictData
-XTemplateHaskell
-XTemplateHaskellQuotes
-XTraditionalRecordSyntax
-XTransformListComp
-XTupleSections
-XTypeApplications
-XTypeInType
-XTypeFamilies
-XTypeOperators
-XTypeSynonymInstances
-XUnboxedTuples
-XUnboxedSums
-XUndecidableInstances
-XUndecidableSuperClasses
-XUnicodeSyntax
-XUnliftedFFITypes
-XViewPatterns
-XNoAllowAmbiguousTypes
-XNoAlternativeLayoutRule
-XNoAlternativeLayoutRuleTransitional
-XNoArrows
-XNoAutoDeriveTypeable
-XNoBangPatterns
-XNoBinaryLiterals
-XNoCApiFFI
-XNoCPP
-XNoConstrainedClassMethods
-XNoConstraintKinds
-XNoDataKinds
-XNoDatatypeContexts
-XNoDefaultSignatures
-XNoDeriveAnyClass
-XNoDeriveDataTypeable
-XNoDeriveFoldable
-XNoDeriveFunctor
-XNoDeriveGeneric
-XNoDeriveLift
-XNoDeriveTraversable
-XNoDerivingStrategies
-XNoDerivingVia
-XNoDisambiguateRecordFields
-XNoDoAndIfThenElse
-XNoBlockArguments
-XNoDoRec
-XNoDuplicateRecordFields
-XNoEmptyCase
-XNoEmptyDataDecls
-XNoEmptyDataDeriving
-XNoExistentialQuantification
-XNoExplicitForAll
-XNoExplicitNamespaces
-XNoExtendedDefaultRules
-XNoFlexibleContexts
-XNoFlexibleInstances
-XNoForeignFunctionInterface
-XNoFunctionalDependencies
-XNoGADTSyntax
-XNoGADTs
-XNoGHCForeignImportPrim
-XNoGeneralizedNewtypeDeriving
-XNoGeneralisedNewtypeDeriving
-XNoImplicitParams
-XNoImplicitPrelude
-XNoImpredicativeTypes
-XNoIncoherentInstances
-XNoTypeFamilyDependencies
-XNoInstanceSigs
-XNoApplicativeDo
-XNoInterruptibleFFI
-XNoJavaScriptFFI
-XNoKindSignatures
-XNoLambdaCase
-XNoLiberalTypeSynonyms
-XNoMagicHash
-XNoMonadComprehensions
-XNoMonadFailDesugaring
-XNoMonoLocalBinds
-XNoMonoPatBinds
-XNoMonomorphismRestriction
-XNoMultiParamTypeClasses
-XNoMultiWayIf
-XNoNumericUnderscores
-XNoNPlusKPatterns
-XNoNamedFieldPuns
-XNoNamedWildCards
-XNoNegativeLiterals
-XNoHexFloatLiterals
-XNoNondecreasingIndentation
-XNoNullaryTypeClasses
-XNoNumDecimals
-XNoOverlappingInstances
-XNoOverloadedLabels
-XNoOverloadedLists
-XNoOverloadedStrings
-XNoPackageImports
-XNoParallelArrays
-XNoParallelListComp
-XNoPartialTypeSignatures
-XNoPatternGuards
-XNoPatternSignatures
-XNoPatternSynonyms
-XNoPolyKinds
-XNoPolymorphicComponents
-XNoQuantifiedConstraints
-XNoPostfixOperators
-XNoQuasiQuotes
-XNoRank2Types
-XNoRankNTypes
-XNoRebindableSyntax
-XNoRecordPuns
-XNoRecordWildCards
-XNoRecursiveDo
-XNoRelaxedLayout
-XNoRelaxedPolyRec
-XNoRoleAnnotations
-XNoScopedTypeVariables
-XNoStandaloneDeriving
-XNoStarIsType
-XNoStaticPointers
-XNoStrict
-XNoStrictData
-XNoTemplateHaskell
-XNoTemplateHaskellQuotes
-XNoTraditionalRecordSyntax
-XNoTransformListComp
-XNoTupleSections
-XNoTypeApplications
-XNoTypeInType
-XNoTypeFamilies
-XNoTypeOperators
-XNoTypeSynonymInstances
-XNoUnboxedTuples
-XNoUnboxedSums
-XNoUndecidableInstances
-XNoUndecidableSuperClasses
-XNoUnicodeSyntax
-XNoUnliftedFFITypes
-XNoViewPatterns
-XHaskell98
-XHaskell2010
-XUnsafe
-XTrustworthy
-XSafe
-XGenerics
-XNoGenerics
-?
--help
-V
--version
--numeric-version
--info
--show-options
--supported-languages
--supported-extensions
--show-packages
--print-project-version
--print-project-git-commit-id
--print-booter-version
--print-stage
--print-build-platform
--print-host-platform
--print-target-platform
--print-have-interpreter
--print-object-splitting-supported
--print-have-native-code-generator
--print-support-smp
--print-unregisterised
--print-tables-next-to-code
--print-rts-ways
--print-leading-underscore
--print-debug-on
--print-libdir
--print-global-package-db
--print-c-compiler-flags
--print-c-compiler-link-flags
--print-ld-flags
--show-iface
-c
-M
-E
-C
-S
--make
--backpack
--interactive
--abi-hash
-e
--frontend

r/haskelltil • • Feb 14 '15

language Constructor names can be matched like this: "f Just{} = True" instead of "f (Just _) = True"

14 Upvotes

Let's say you've got an ADT with lots of constructors, each having several fields:

data ADT = Foo Int Int Bool String | Bar String [String] | ...

Now you want to write an isFoo function. You could do it like this:

isFoo (Foo _ _ _ _) = True
isFoo _             = False

but it's kinda annoying that all these useless fields have to be specified and new underscores have to be added when a field is added.

Behold, the alternative solution:

isFoo Foo{} = True
isFoo _     = False

It exploits the syntax of pattern matches for records, as well as the fact that records are ordinary ADTs in Haskell, as well as the quirk of record braces which states that they bind tighter than everything else (including function application).


r/haskelltil • • Mar 08 '15

gotcha “[x| blah |]” syntax (used for Template Haskell) is rather restrictive when it comes to “x”

3 Upvotes
  • x can't be an expression; [foo True| blah |] isn't allowed

  • x can't be called “e”, “t”, “d” or “p”

  • there can't be any spaces before or after x

The corresponding page of documentation: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/template-haskell.html#th-quasiquotation.


r/haskelltil • • Mar 19 '15

meta The author of the most upvoted submission gets a month of Reddit gold (deadline: March 31)

4 Upvotes

Moderators' submissions don't count, of course.

I mean, my submissions don't count. Why would there even be a need for this contest if there was anyone beside me who submitted things?

Edit: /u/massysett (:sprint in GHCi lets you view thunks) won.


r/haskelltil • • Jun 30 '19

Some useful functions for fgl - Functional Graph Library

4 Upvotes

Daniel Wagner, answering my question posted on Stackoverflow about NodeMapM, made the following observation:

"Re-adding a node [to a graph] deletes all edges out of that node. See the source of insNode, which is what insMapNodesM eventually calls: insNode (v,l) = (([],v,l,[])&)

The two empty lists are for incoming and outgoing edges."

For this reason, examples ex1a and ex1b give different results.

The following functions are based on a different version of insNode, A VERSION WHICH PRESERVE THE ADJOINTS OF A PRE-EXISTING NODE. Moreover, this version of insNode verifies the equality between the node's old and new label, giving an error message in case they were different.

So now ex1a is equal to ex2, which differed from ex1b only because it uses the modified (and 'conservative') version of insMapNodesM.

** ALL NEW FUNCTIONS ARE SIMPLY MODIFIED VERSIONS OF THOSE PRESENT IN THE fgl LIBRARY **

import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.PatriciaTree -- needed only for examples
import Data.Graph.Inductive.NodeMap
import Data.List (foldl')
import Control.Monad.Trans.State (get,put)
import Data.Maybe (fromJust)

insNode' :: (DynGraph g, Eq a) => (Node, a) -> g a b -> g a b
insNode' (v,l) g
  | not (gelem v g) = ([],v,l,[]) & g
  | fromJust (lab g v) /= l = error ("Label of node " ++ show v ++ " is different from the new one")
  | otherwise = g
                   
insNodes' :: (Eq a, DynGraph gr) => [LNode a] -> gr a b -> gr a b
insNodes' vs g = foldl' (flip insNode') g vs
                   
insMapNode' :: (Ord a, DynGraph g) => NodeMap a -> a -> g a b -> (g a b, NodeMap a, LNode a)
insMapNode' m a g =
    let (n, m') = mkNode m a
    in (insNode' n g, m', n)
    
insMapNodes' :: (Ord a, DynGraph g) => NodeMap a -> [a] -> g a b -> (g a b, NodeMap a, [LNode a])
insMapNodes' m as g =
    let (ns, m') = mkNodes m as
    in (insNodes' ns g, m', ns)

insMapNodes_' :: (Ord a, DynGraph g) => NodeMap a -> [a] -> g a b -> g a b
insMapNodes_' m as g =
    let (g', _, _) = insMapNodes' m as g
    in g'

insMapNodeM' :: (Ord a, DynGraph g) => a -> NodeMapM a b g (LNode a)
insMapNodeM' = liftM1' insMapNode'

insMapNodesM' :: (Ord a, DynGraph g) => [a] -> NodeMapM a b g [LNode a]
insMapNodesM' = liftM1' insMapNodes'

liftM1' :: (NodeMap a -> c -> g a b -> (g a b, NodeMap a, d)) -> c -> NodeMapM a b g d
liftM1' f c =
    do (m, g) <- get
       let (g', m', r) = f m c g
       put (m', g')
       return r

-- -------------------- EXAMPLES --------------------

p1 = ("P1", ['A','B','C','D'])
p2 = ("P2", ['B','C','E','F'])


toLedges :: (a, [b]) -> [(b,b,a)]
toLedges (le,xs) = zipWith (\x1 x2 -> (x1,x2,le)) (init xs) (tail xs)


ex1a :: NodeMapM Char String Gr ()
ex1a =    insMapNodesM  (snd p1)
       >> insMapNodesM  (snd p2)
       >> insMapEdgesM  (toLedges p1)
       >> insMapEdgesM  (toLedges p2)

-- run empty ex1a :: ((),(NodeMap Char, Gr Char String))

ex1b :: NodeMapM Char String Gr ()
ex1b =    insMapNodesM  (snd p1)
       >> insMapEdgesM  (toLedges p1)
       >> insMapNodesM  (snd p2)
       >> insMapEdgesM  (toLedges p2)
         
-- run empty ex1b :: ((),(NodeMap Char, Gr Char String))

ex2 :: NodeMapM Char String Gr ()
ex2 =    insMapNodesM'  (snd p1)
      >> insMapEdgesM  (toLedges p1)
      >> insMapNodesM'  (snd p2)
      >> insMapEdgesM  (toLedges p2)
         
-- run empty ex2 :: ((),(NodeMap Char, Gr Char String))

r/haskelltil • • Apr 22 '18

Interleaving stuff with other stuff forms a Semigroup

4 Upvotes

https://twitter.com/Profpatsch/status/986793219718549505

module Main where

import Data.Semigroup
import Data.List.NonEmpty
import Data.Tree
import Data.Foldable

newtype Sep a = Sep { unSep :: a -> a }

instance Semigroup a => Semigroup (Sep a) where
  (Sep f) <> (Sep g) = Sep
    $ \sep -> f sep <> sep <> g sep

instance (Monoid a, Semigroup a) => Monoid (Sep a) where
  mempty = Sep (const mempty)
  mappend = (<>)

interleave :: Semigroup a => a -> NonEmpty a -> a
interleave = flip outerleave
  where outerleave = unSep . sconcat . fmap (Sep . const)


ex1 = interleave " "
  $ "somebody" :| [ "once", "told", "me"
  , "the", "world", "is", "gonna", "roll", "me" ]

-- "somebody once told me the world is gonna roll me"

It also forms a Monoid, though I’m not sure if the instance is helpful in a lot of cases:

combine :: (Semigroup a, Monoid a, Traversable t) => a -> t a -> a
combine = flip umbine
  where umbine = unSep . fold . fmap (Sep . const)

ex2 = combine "|"
  $ Node "cut" [Node "my" [Node "life" []], Node "into" [Node "pieces" []],
      Node "this" [], Node "is" [], Node "my" [], Node "last" [], Node "resort" []]

-- "cut|my|life|||||into|pieces|||||this|||is|||my|||last|||resort||||"


main = do
  print ex1
  print ex2

As always, Kmett did it first.


r/haskelltil • • Jan 10 '20

; (U+037E) is a valid operator

15 Upvotes

; can be used as an operator so Category could in theory be

type  Category :: Cat ob -> Constraint
class Category cat where
  id  :: cat a a
  (;) :: cat a b
      -> cat b c
      -> cat a c

The symbol in question is not a semi comma ;

>> validOperator = Text.Read.Lex.isSymbolChar
>> validOperator ';'
False

but a GREEK QUESTION MARK

>> validOperator ';'
True
>> validOperator '\x037E'
True

This allows reading in a more natural left-to-right way.

This is apparently a series of posts of me exploring confusable characters:


r/haskelltil • • Mar 19 '15

idiom The Maybe monad and "do" notation can be used together for easier, more composable pattern matching.

5 Upvotes

Haskell has an obscure rule that when you bind to a pattern on the left-hand of a <- token in do notation, if the pattern match fails the fail function is called rather than the error function. Since the Maybe monad instantiates fail as const Nothing, you can write functions like this:

sum3digits x = maybe "must be a 3 digit number" ("OK: "++) $
    do { [a,b,c] <- Just $ show (x::Int); Just $ show (fromEnum a+fromEnum b+fromEnum c-3*fromEnum '0'); }

This only works with do notation. Using ordinary bind >>= does not behave this way.

Then you can use the MonadPlus and Alternative combinators to sift through complex data structures. I have found this to be slightly more composable than just using case statements.

For example, say you have a function that has an enormous case statement:

data Lexeme = LxInt Int | LxStr String | LxOp Lexeme Char Lexeme

simplify :: Lexeme -> Maybe Lexeme
simplify x = case x of
    LxOp (LxInt a) op (LxInt b) -> case op of
        '+' -> Just $ LxInt (a+b)
        '-' -> Just $ LxInt (a-b)
        '*' -> Just $ LxInt (a*b)
        '/' -> Just $ LxInt (a/b)
        '%' -> Just $ LxInt (a%b)
        _   -> Nothing
    LxOp (LxStr a) '+' (LxStr b) -> Just $ LxStr (a++b)
    LxOp a op b -> LxOp <$> simplify a <*> pure op <*> simplify b
    _ -> Nothing

This large function can be decomposed into three simpler, more composable functions:

data Lexeme = LxInt Int | LxStr String | LxOp Lexeme Char Lexeme

simplifyInts :: Lexeme -> Maybe Lexeme
simplifyInts = do
    (LxOp (LxInt a) op (LxInt b)) <- Just x
    msum [ do { '+' <- Just op; Just $ LxInt (a+b); },
           do { '-' <- Just op; Just $ LxInt (a-b); },
           do { '*' <- Just op; Just $ LxInt (a*b); },
           do { '/' <- Just op; Just $ LxInt (div a b) },
           do { '%' <- Just op; Just $ LxInt (mod a b) }
         ]

simplifyStrs :: Lexeme -> Maybe Lexeme
simplifyStrs = do
    (LxOp (LxStr a) '+' (LxStr b)) <- Just x
    Just $ LxStr (a++b)

simplify :: Lexeme -> Maybe Lexeme
simplify x = simplifyInts x <|> simplifyStrs x <|> do
    (LxOp a op b) <- x
    LxOp <$> simplify a <*> pure op <*> simplify b

And notice it can be further decomposed by breaking down the msum statement in simplifyInts. And personally, I think it is easier to write and read than:

simplifyInts :: Lexeme -> Maybe Lexeme
simplifyInts (LxOp (LxInt a) op (LxInt b)) = do
    ...
simplifyInts _ = Nothing

r/haskelltil • • Mar 13 '15

gotcha “inRange (a,b) x” is not always the same as “a<=x && x <= b”

5 Upvotes

There's a function in Data.Ix – inRange – which is occasionally useful. It lets you replace annoying comparisons:

> inRange (1,3) 2
True

> inRange (1,3) 5
False

However, it's important to know that it's not merely a shortcut for a <= x && x <= b, but a function used to simplify working with array indexes. For that reason, it treats tuples specially:

> (1,3) < (2,2)
True

> (2,2) < (3,1)
True

but:

> inRange ((1,3),(3,1)) (2,2)
False

(You can still safely use it for ordinary numeric types, tho.)


r/haskelltil • • Jan 30 '15

etc The kind of “(->)” used to be “?? -> ? -> *”

5 Upvotes

In old GHC (before 7.4, I think) you could get this:

> :k (->)
(->) :: ?? -> ? -> *

The reason was that for GHC all those things were different:

and the restriction on unboxed tuples was such that you couldn't have them as function arguments, only as function results. So, ? was a kind for “anything”, and ?? was a kind for “# or *”. Then unboxed tuples were unified with unboxed values (so you can use them as function arguments now), and now (->) has kind ? -> ? -> *.

Why doesn't it show as ? -> ? -> *, then?

> :k (->)
(->) :: * -> * -> *

Because for whatever reason (I don't know, why) GHC defaults to * whenever possible. For instance:

> :k Int# -> Int#
Int# -> Int# :: *

but

> :k (->) Int# Int#

<interactive>:1:6:
    Expecting a lifted type, but ‘Int#’ is unlifted
    In a type in a GHCi command: (->) Int# Int#

Or with a type synonym:

> type F a = Int# -> a

> :k F
F :: * -> *

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 17 '15

thing Functions «div'» and «mod'» from Data.Fixed are like «div» and «mod», but for real numbers

7 Upvotes

Observe, fractional integral division:

> import Data.Fixed

> 3.5 `div'` 0.3
11

> 3.5 `mod'` 0.3
0.2

No idea what it could be needed for, but nice to know.

Links: div', mod'.


r/haskelltil • • Feb 12 '15

extension When importing something using PackageImports, special name "this" can be used to refer to the package being built

7 Upvotes

Like this:

{-# LANGUAGE PackageImports #-}

import "this" Data.Monoid  -- local version with added goodies

I guess it could be used to reduce the amount of CPP in packages, for one.


r/haskelltil • • May 19 '19

Data.Functor.Contravariant: some simple applications and some questions

7 Upvotes

These days I have tried to better understand this library and its potential use.

In the description of the Contravariant class there is an example relating to the banking world.

So I used some library functions in the same context.

I could not find examples of use of the following functions:

  1. (>$) and its inverse ($<)

    ex. getPredicate ((>$) 0 isNegative) "Hello!"

    -- > False

  2. newtype Equivalence a. I mean, something not trivial.

  3. phantom: Is there something that is Functor and Contravariant? Example in banking field?

"Dual arros" newtype Op a b: I only found something curious about strings, but nothing interesting about numbers.

Can you give me some suggestions to complete my work?

import Data.Functor.Contravariant
import qualified Control.Category as Cat
import Data.Semigroup
import qualified Data.List.NonEmpty as N

type Client = String
type Balance = Integer
type ClientBalance = (Client,Balance)

clientsBankFoo :: [ClientBalance] -- sorted
clientsBankFoo = [("Olivia",5000),("Jack",200),("Harry",-10000),("Isabella",-150000),("George",-1000000)]

clientsBankBar :: [ClientBalance] -- sorted
clientsBankBar = [("Mary",7000),("Ron",2000),("Jim",-100000),("Sam",-10000000)]

personBankBalance :: [ClientBalance] -> Client -> Balance
personBankBalance clients_pos client =
    case lookup client clients_pos of
        Nothing -> error "Not a client."
        Just n -> n

-- -------------------- newtype Predicate a --------------------

isNegative :: Predicate Integer
isNegative = Predicate (<0)

isBigNum :: Predicate Integer
isBigNum = Predicate $ (1000<) . abs
-- ex. getPredicate (bigNum <> negative) $ (-10)
-- > False

bigOverdrawn :: [ClientBalance] -> Client -> Bool
bigOverdrawn =  \clients -> getPredicate (contramap (personBankBalance clients) (isBigNum <> isNegative)) 
-- ex. bigOverdrawn clientsBankFoo "Isabella"
-- > True
--  ex. bigOverdrawn clientsBankFoo "Harry"
-- > False

bigOverdrawn' :: [ClientBalance] -> Client -> Bool
bigOverdrawn' =  getPredicate . (>$< isBigNum <> isNegative) . personBankBalance
-- ex. bigOverdrawn' clientsBankFoo "Isabella"
-- > True

bigOverdrawn2 :: [ClientBalance] -> Client -> Bool
bigOverdrawn2 = getPredicate . (isBigNum <> isNegative >$$<) . personBankBalance
-- ex. bigOverdrawn2 clientsBankFoo "Harry"
-- > True

-- -------------------- newtype Comparison a --------------------

compareWealth :: Comparison ClientBalance 
compareWealth = Comparison $ \(c1,b1) (c2,b2) -> compare b1 b2
-- ex. getComparison compareWealth ("Harry",(-10000)) ("Olivia",(5000))
-- > LT

comparesTheWealthiestClientsOf :: [ClientBalance] -> [ClientBalance] -> Ordering
comparesTheWealthiestClientsOf = getComparison (contramap (head) compareWealth) 
-- ex. comparesTheWealthiestClientsOf clientsBankFoo clientsBankBar
-- > LT

-- -------------------- newtype OP a b --------------------

prettyClient (c,b) =  getOp (sconcat (Op (++ " " ++ c ++ "\t") N.:| [Op (++" "),Op ((show b ++ "\t") ++)])) "=="

prettyClients cs = mapM_ (putStrLn . prettyClient) cs
-- ex. prettyClients clientsBankFoo

-- > == Olivia	 == 5000	 ==
-- > == Jack	 == 200	     ==
-- > == Harry	 == -10000	 ==
-- > == Isabella == -150000	 ==
-- > == George	 == -1000000 ==

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 • • Mar 08 '15

tools GHC doesn't support mutually recursive modules (i.e. when 2 or more modules depend on each other) well; JHC does

8 Upvotes

GHC wouldn't be able to compile this:

-- A.hs
module A where
import B
ab = 'a' : ba

-- B.hs
module B where
import A
ba = 'b' : ab

Okay, well, there is a way to do it – using hi-boot files – but it's awkward and nobody really uses it.

In comparison, JHC can compile such modules without any problems.


r/haskelltil • • Nov 25 '17

Mutation's ok

8 Upvotes

This is more meta, but is meaningful enough to me that I thought I'd share.

Since discovering haskell I've developed a strong puritan view toward my code.

Yet I do ascribe to the view:

  1. Make it. 2. Make it right. 3. Make it optimized.

So, I've been playing a bit more with mutable variables, and they really help me with getting a project running quickly. Especially, I've been playing with the ReaderT design pattern, and just gotta say, thanks to the community for helping me relax my perfectionism a bit :)


r/haskelltil • • May 17 '15

gotcha With BangPatterns enabled, you might stumble upon cryptic errors if you decide to define a “!” operator

8 Upvotes

Example 1:

{-# LANGUAGE BangPatterns #-}

f ! x = f + x

results in:

Occurs check: cannot construct the infinite type: a ~ a -> a …
    Relevant bindings include
      x :: a
      f :: a -> a
    In the first argument of ‘(+)’, namely ‘f’
    In the expression: f + x

Example 2:

{-# LANGUAGE BangPatterns #-}

(x:xs) ! n = x : drop n xs

results in

Parse error in pattern: (x : xs)

To fix both, just define ! non-infix: (!) f x = ....

This behavior is described in the GHC manual.


r/haskelltil • • Jan 28 '15

etc “Leksah” is “haskel” backwards [just in case: Leksah is a Haskell IDE written in Haskell]

8 Upvotes

r/haskelltil • • Mar 22 '15

tools Create a .ghci file to automatically load useful modules, etc. every time GHCi starts

9 Upvotes

If you create a file called “.ghci” in your home folder, you can put commands there that would be executed every time GHCi starts. For instance:

This prevents the prompt from growing every time you import a module:

:set prompt "> "

This enables some useful extensions:

:set -XPackageImports
:set -XOverloadedStrings
:set -XScopedTypeVariables -XRankNTypes

This imports modules:

import Control.Applicative
import Control.Monad
import Data.Monoid

import Data.Maybe
import Data.List
import Data.Bool

import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Text as T

(Or you can just import all functions from base using the base-prelude package.)

This defines some shortcuts:

let fi = fromIntegral
let (&) = flip ($)  -- not in base yet, but will be in GHC 7.10

Finally, you can define macros as well – here's a rather extensive collection of useful ones.

(And by the way, you can also create .ghci files for individual projects.)