Haskell nested where clause

I am a beginner coder in haskell, performing an exercise from the first chapter of this amazing book: http://book.realworldhaskell.org/read/getting-started.html I ran into this problem:

-- test comment main = interact wordCount where wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n") where ls = lines input ws = length words input cs = length input wonderbox:ch01 manasapte$ runghc WC < quux.txt WC.hs:5:9: parse error on input 'where' 

Why can't I nest my pages?

+6
source share
3 answers

Since your second where tied to the wordCount definition, you need to indent it more than it does. (Although after that you will still have some other errors.)

+7
source

Others have already answered. I will just add a few more explanations.

To simplify the bit, the Haskell indent rule:

  • Some keywords trigger a block of things ( where , let , do , case ... of ).
  • Find the first word after such keywords and pay attention to its indent. Name the column in which it is located.
  • Adjust the line exactly on the vault to define a new record in the block.
  • Begin the line after the rotation to continue the recording started in the previous lines.
  • Start the line before the pivot point to end the block.

Hence,

 where wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n") where ls = lines input ws = length words input cs = length input 

Actually mean

 where { wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n") ; where { -- same column, new entry ls = lines input ; -- same column, new entry ws = length words input ; -- same column, new entry cs = length input } } 

which treats the second where as a separate definition not related to wordCount . If we print this more:

 where { wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n") where { -- after the pivot, same entry ls = lines input ; ws = length words input ; cs = length input } } 
+5
source

the indentation was wrong, here is the working version:

 -- test comment import Data.List main = interact wordCount where wordCount input = unlines $ [concat $ intersperse " " (map show [ls, ws, cs])] where ls = length $ lines input ws = length $ words input cs = length input 
+2
source

Source: https://habr.com/ru/post/983840/


All Articles