What is wrong in this Haskell function? - haskell

I decided to dive in functional programming world recently, and a friend told me about Haskell. I started my own researches on the language particularity and soon I got the main concepts. Then, I started working with lists and decided to rewrite some existent functions, just to practice.
I made my version of the reverse function, and called it revert. The function is defined as below:
revert :: [a] -> [a]
revert [] = []
revert a = revert (tail a) ++ [head a]
It works perfectly for me, as you can see in the image:
But then, I decided to make another test, receiving the result of the revert function on the same variable that I passed as a parameter, as you can see below:
It seems to execute the function normally, but when I check the value of x, it looks like it goes into a loop, and I need to interrupt the operation.
If I set the value on another variable, it works perfectly:
let y = revert x
Why does it happen? Is it some concept of functional programming that I am missing? Or some peculiarity with Haskell? I did some googling but was not able to get to an answer
PS: Sorry for the bad english

You're defining
x = revert x
So, substituting on the right, this gives
x = revert (revert x)
And so on. Another example would be
a = a + 1
To find out what a is, we need to evaluate the right hand side of the definition.
a = (a + 1) + 1
a = ((a+1)+1) + 1
And so on.
Bootom line: Haskell's = is very different from = in languages like C#, where it means assignment. In Haskell it means is defined as and this means we can substitute any occurance of an identifier with its definition without changing the meaning of the program. This is called referential transpareny.

Related

Turning a list into a set of coordinates [Haskell]

I am a starting out programmer and have my first few programming classes. We started off with functional programming, in this case using Haskell. I've managed to complete a few assignments already, but seem to have gotten stuck in one point and was hoping to get some help with it.
In order to not bore you with the entire code, my program right now is extracting a list of commands from a text file. I need to turn this list into a set of coordinates. What I mean is something along the lines of:
function :: [String] -> (Int, Int, Char)
where the function will receive, for example, the list ["0 0 N"] and output the coordinates and direction (0, 0, N).
I tried doing:
function [x y o] = (show x, show y, read o)
which would work if it were just Integers. I can't seem to get the Char part to work. I appologize if it's such a noobie question, but bear with me, please, I'm really new to all of this.
Thank you and best regards!
For your specific test case this should work:
function [(x:' ':y:' ':o:_)] = (read [x], read [y], o)
If your string contains spaces you need to match on them as well if you want to do it like that.
But that's probably not what you actually want. It would break for inputs like ["12 23 S"] or ["3 5 W", "2 8 E"].
If your input is actually a list of Strings like your signature says you should probably write two functions: One that deals with a single String and one that applies your other function to all Strings in the list. Look at the functions map and words and think about how you can use them to solve your problem.

Alpha conversion on a Haskell expression

Given a Haskell expression, I'd like to perform alpha conversion, ie. rename some of the non free variables.
I've started implementing my own function for this, which works on a haskell-src-exts Exp tree, however it turns out to be surprisingly nontrivial, so I can't help wondering - is there an established easy-to-use library solution for this kind of source conversion? Ideally, it should integrate with haskell-src-exts.
This is one of the problems where the "Scrap Your Boilerplate" style generic libraries shine!
The one I'm most familiar with is the uniplate package, but I don't actually have it installed at the moment, so I'll use the (very similar) functionality found in the lens package. The idea here is that it uses Data.Data.Data (which is the best qualified name ever) and related classes to perform generic operations in a polymorphic way.
Here's the simplest possible example:
alphaConvert :: Module -> Module
alphaConvert = template %~ changeName
changeName :: Name -> Name
changeName (Ident n) = Ident $ n ++ "_conv"
changeName n = n
The (%~) operator is from lens and just means to to apply the function changeName to everything selected by the generic traversal template. So what this does is find every alphanumeric identifier and append _conv to it. Running this program on its own source produces this:
module AlphaConv where
import Language.Haskell.Exts
import Control.Lens
import Control.Lens.Plated
import Data.Data.Lens
instance Plated_conv Module_conv
main_conv
= do ParseOk_conv md_conv <- parseFile_conv "AlphaConv.hs"
putStrLn_conv $ prettyPrint_conv md_conv
let md'_conv = alphaConvert_conv md_conv
putStrLn_conv $ prettyPrint_conv md'_conv
alphaConvert_conv :: Module_conv -> Module_conv
alphaConvert_conv = template_conv %~ changeName_conv
changeName_conv :: Name_conv -> Name_conv
changeName_conv (Ident_conv n_conv)
= Ident_conv $ n_conv ++ "_conv"
changeName_conv n_conv = n_conv
Not terribly useful since it doesn't distinguish between identifiers bound locally and those defined in an outside scope (such as being imported), but it demonstrates the basic idea.
lens may seem a bit intimidating (it has a lot more functionality than just this); you may find uniplate or another library more approachable.
The way you'd approach your actual problem would be a multi-part transformation that first selects the subexpressions you want to alpha-convert inside of, then uses a transformation on those to modify the names you want changed.

How to use Template Haskell to get the body of function?

Currently I'm trying to do a translation from a Haskell subset without having to deal with all the parsing, typechecking etc. issues. Documentation didn't help me to figure out a function to get the function's body (all the definitions) by its name.
Context for this call should look something like
fac 0 = 1
fac x = z * fac (x - 1)
getBody = ...
main = do
x <- runQ $ getBody [| fac |]
print x
Does anyone knows
whether there are some good and up to date docs on TH (not the reference on Hackage) or
how to make getBody?
In general, the way to find the definition of something with TH is using the reify function. However:
You can't use reify at run-time via runQ. The information it needs is not available except during compilation.
Currently, using reify to get function definitions is not implemented due to lack of interest anyway.
Looks like you'll need to find another route. Have you considered using the haskell-src-exts package for parsing and/or the GHC API or something based on it?

Which Monad do I need?

This is something of an extension to this question:
Dispatching to correct function with command line arguments in Haskell
So, as it turns out, I don't have a good solution yet for dispatching "commands" from the command line to other functions. So, I'd like to extend the approach in the question above. It seems cumbersome to have to manually add functions to the table and apply the appropriate transformation function to each function so that it takes a list of the correct size instead of its normal arguments. Instead, I'd like to build a table where I'll add functions and "tag" them with the number of arguments it needs to take from the command line. The "add" procedure, should then take care of composing with the correct "takesXarguments" procedure and adding it to the table.
I'd like to be able to install "packages" of functions into the table, which makes me think I need to be able to keep track of the state of the table, since it will change when packages get installed. Is the Reader Monad or the State Monad what I'm looking for?
No monad necessary. Your tagging idea is on the right track, but that information is encoded probably in a different way than you expected.
I would start with a definition of a command:
type Command = [String] -> IO ()
Then you can make "command maker" functions:
mkCommand1 :: (String -> IO ()) -> Command
mkCommand2 :: (String -> String -> IO ()) -> Command
...
Which serves as the tag. If you don't like the proliferation of functions, you can also make a "command lambda":
arg :: (String -> Command) -> Command
arg f (x:xs) = f x xs
arg f [] = fail "Wrong number of arguments"
So that you can write commands like:
printHelloName :: Command
printHelloName = arg $ \first -> arg $ \last -> do
putStrLn $ "Hello, Mr(s). " ++ last
putStrLn $ "May I call you " ++ first ++ "?"
Of course mkCommand1 etc. can be easily written in terms of arg, for the best of both worlds.
As for packages, Command sufficiently encapsulates choices between multiple subcommands, but they don't compose. One option here is to change Command to:
type Command = [String] -> Maybe (IO ())
Which allows you to compose multiple Commands into a single one by taking the first action that does not return Nothing. Now your packages are just values of type Command as well. (In general with Haskell we are very interested in these compositions -- rather than packages and lists, think about how you can take two of some object to make a composite object)
To save you from the desire you have surely built up: (1) there is no reasonable way to detect the number of arguments a function takes*, and (2) there is no way to make a type depend on a number, so you won't be able to create a mkCommand which takes as its first argument an Int for the number of arguments.
Hope this helped.
In this case, it turns out that there is, but I recommend against it and think it is a bad habit -- when things get more abstract the technique breaks down. But I'm something of a purist; the more duct-tapey Haskellers might disagree with me.

Functions in Haskell

I'm new to functional programming. I have a basic question.
I'm using the Hugs interpreter,
I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.
fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)
This gives me a syntax error :-S
ERROR - Syntax error in input (unexpected `=')
I assume you type this right into the interactive prompt. Sadly, these are relatively primitive in Haskell - complex definitions, such as fact, can't be entered at the prompt, at least not in the same way you'd normally write them.
You need to put function definitions etc. into modules, then load those via (e.g.) :load fact.hs. There are resources for Hugs specifically that provide more information on this and other topic (I used http://cvs.haskell.org/Hugs/pages/hugsman/index.html to check my assumptions).
Also note that indentation matters, so the code won't work the way you posted it here even when in a module. Those tutorials will have correct versions. If not, they're useless and you should forget them.
The syntax is incorrect. In Haskell, whitespace matters, much like it does in Python. More specifically, if you have text that starts on the first column of a line, the interpreter will think it's a top-level declaration. The correct syntax would be (for example):
fact :: Int -> Int
fact n = if n == 0
then 1
else n * fact (n-1)
You could also put the if in one line if you'd like to. So if you're using an interactive prompt you could do:
λ> let fact n = if n == 0 then 1 else n * fact (n-1)
Notice that you'll need to use let in order to define functions on the prompt (at least this is how it's done in GHCi, I'm not sure about Hugs). You'll be better off putting them in a separate file and then loading that in the interpreter. But anyway, a much nicer solution would use pattern-matching in my opinion anyway:
fact :: Int -> Int
fact 0 = 1
fact n = n * fact (n-1)
Here, the interpreter would pattern-match the first argument of the function against the possible cases listed. So if the first argument is null, the result if 1, otherwise apply the function recursively.
Create a file named, for example, fact.hs
-- copying cedric's nicely formatted code
fact :: Int -> Int
fact n = if n == 0
then 1
else n * fact (n-1)
That's all that really needs to be there. When you want to make real modules, you should do some extra stuff.
Now, open up ghci from the same folder. At the ghci prompt, use the :l command to load the "module"
Prelude> :l fact.hs
[1 of 1] Compiling Main ( fact.hs, interpreted )
Ok, modules loaded: Main.
*Main> fact 3
6
*Main> fact 10
3628800
I assume it's a very similar process with Hugs. I think hugs requires the file name to be capitalized. ghci simply creates a "Main" module and puts your code in it; that's why the prompt changes from Prelude> to *Main>
When I work on small Haskell functions, I usually keep two terminals open: one for vim and one for ghci. When I change the file in vim (and save it), I just use :r in ghci to reload the new definitions.
*Main> :r
Ok, modules loaded: Main.
It should be mentioned that the most elegant way to write this function is:
fac n = product [1..n]
See http://www.willamette.edu/~fruehr/haskell/evolution.html for details.

Resources