What does backslash space mean in Haskell - haskell

I know that something like \x->x+1 is an anonymous function definition that gets an x and adds one to it. But I saw the expression return x = (\ r -> x) when I was reading an article here.
What does (\ r -> x) mean? Why after backslash is empty?

There is no difference: \ r -> x or \r -> x have the same meaning, much as 1+1 and 1 + 1 have the same meaning. Whitespace after \ is irrelevant.
So, return x is just \r -> x, which is a function which takes a parameter r, ignores it, and yields x.
Moreover, since r gets ignored, we tend to write \ _ -> x (or const x - which is defined as const x _ = x) instead.

Related

Can we use 'where' in a lambda function in Haskell?

I was wondering if we can use where in an anonymous function or not. I tried to do it in this way:
\x -> k where k = x+1
But this gives a parse error on 'where'.
You can use where in certain expressions within a lambda expression, but not just inside.
f = \x ->
case x of
Nothing -> 12
Just y -> z * 2
where z = y + 7

Transform an attoparsec parser into a parser which fails if the number of bytes it consumes is not of a certain length

Say I have an attoparsec parser, x.
I am looking to create a function f :: Int -> Parser a -> Parser a, such that if y = f n x, then:
y fails if x fails
y fails if x succeeds and x does not consume n bytes
y succeeds otherwise
How would I go about doing this?
You can use match to implement it:
f n x = do
(bs, res) <- match x
guard (BS.length bs >= n)
return res
You should check that this interacts with (<|>) in an acceptable way before putting it to heavy use.

Haskell passing empty Character to a function

I'm working in Haskell in two functions:
Basically I want to get the character before matching a specific character in a given string
This is my code:
before :: Char -> [Char] -> Char
before x str = trackelement x ' ' str
trackelement :: Char -> Char -> [Char] -> Char
trackelement x y (z:zs)
| x == z = y
| otherwise = trackelement x z (zs)
My problem is when I try: before 'l' "luis"
The answer is : ' ' (of course, before 'l' there is nothing), and I would like to be '' or Nothing
I tried passing trackelement x '' str instead of trackelement x ' ' str but I have this error Syntax error on ''str
Could you suggest me something?
The answers shown already are good for getting your code to work, but they don't explain why you get the error you're receiving. The reason why that error was shown is that '' is not valid syntax, since there is no such thing as an "empty character". All characters have value, but Strings can be empty. Remember that type String = [Char], and it's very clear that there can be such a thing as an empty list, but characters always have a value. It's comparable to saying you can have an empty list of Ints, namely [], but you can't have an "empty int", whatever that would mean.
You can use a Maybe:
before :: Char -> [Char] -> Maybe Char
before x str = initialise x str
initialise x (y:xs)
| x == y = Nothing
| otherwise = trackelement x y xs
trackelement :: Char -> Char -> [Char] -> Maybe Char
trackelement x y [] = Nothing
trackelement x y (z:zs)
| x == z = Just y
| otherwise = trackelement x z zs
To take care of the corner case before 'l' "luis", we have to add a new initialiser function. It basically checks if the first character matches the searched one. If it does, we return Nothing, because we checked the first character which obviously does not have a preceding one. Else we just call trackelement and use it's result.
As Zeta mentioned, you can combine the functions, which simplifies everything and takes care of the corner case you are currently experiencing.
before _ [x] = Nothing
before a (x:y:xs)
| a == y = Just x
| otherwise = before a (y:xs)
Just using this function, you noticed you have problems when encountering a word containing more than one letter which is also searched for (before 'a' "amalia" -> Just 'm'). Currently the best solution I know of is again splitting this up into more than one function, which brings us back to the solution at the top.
Match the first two elements instead just head and tail. That way you don't even need trackelement:
before :: Eq a => a -> [a] -> Maybe a
before x (a:b:rest)
| a == x = Nothing
| b == x = Just a
| otherwise = before x (b:rest)
before _ _ = Nothing

Currying Functions Erlang

I'm trying to redo all of my Haskell homework problems using Erlang, and one thing that gets me is how to use a list of functions that don't have all of their parameters.
Example: I'm trying to use this fold, but I don't know how to pass in the functions so that it operates on the accumulator
%%inside my module)
add(X,Y) -> X + Y.
multiply(X,Y) -> X*Y.
Afterwards using this in the command line:
lists:foldl(fun(Function,Accumulator) -> Function(Accumulator) end, 3, [add(3),multiply(5)]).
In Erlang you must call function passing all parameters it requires. But you can easily avoid it by creating an anonymous function which takes only those parameters you need and then calls your function rightly. If you need a function which takes one parameter X and calls function add(3, X) you can create an anonymous function like that:
fun (X) -> add(3, X) end
This is an example for your task:
lists:foldl(fun (Function, Accumulator) -> Function(Accumulator) end, 3,
[fun (X) -> add(3, X) end, fun (X) -> multiply(5, X) end]).
In terms of native Erlang there is not any form of partial evaluation like you want. You will have to create your own fun's to do it. However if you use the Erlando Monad Library then you can use pattern matching to create it. It works by the fact that the erlang compiler lets you play with the AST on compiling code so you can do cool stuff like this.
One can fairly easily write a partial application function which is called analogous way to erlang:apply/3. It lacks the elegance you have in languages that support currying.
-module(partial).
-export([apply/4]).
apply(Module, Name, Arity, Args) when length(Args) < Arity ->
Left = Arity - length(Args),
fun(Args1) when length(Args1) < Left ->
fun(Args2) ->
apply(Module, Name, Arity, Args2 ++ Args1 ++ Args)
end;
(Args1) when length(Args1) > Left ->
erlang:error(badarg);
(Args1) ->
erlang:apply(Module, Name, Args1 ++ Args)
end;
apply(_, _, Arity, Args) when length(Args) > Arity ->
erlang:error(badarg);
apply(Module, Name, _, Args) ->
erlang:apply(Module, Name, Args).
-module(f).
-export([curry/1]).
curry(AnonymousFun) ->
{arity, Arity} =
erlang:fun_info(AnonymousFun, arity),
do_curry(AnonymousFun, Arity, [[], [], []]).
do_curry(Fun, 0, [Fronts, Middle, Ends] = X) ->
% Fronts ++ Middle ++ ")" ++ Ends;
[F, M, E] =
lists:map(fun(L) -> string:join(L, "") end, X),
Fstring =
F ++ "Run(" ++ string:trim(M, trailing, ",") ++ ")" ++ E,
{ok, Tokens, _} =
erl_scan:string(Fstring ++ "."),
{ok, Parsed} =
erl_parse:parse_exprs(Tokens),
FunBinding =
erl_eval:add_binding(
'Run',
Fun,
erl_eval:new_bindings()
),
{value ,CurriedFun, _} =
erl_eval:exprs(Parsed, FunBinding),
CurriedFun;
do_curry(Fun, Arity, [Fronts, Middle, Ends]) ->
VarName = [64 + Arity],
NewFronts = ["fun(" ++ VarName ++ ") -> " | Fronts] ,
NewMiddle = [VarName ++ ","|Middle],
NewEnds = [" end"|Ends],
do_curry(Fun, Arity-1, [NewFronts, NewMiddle, NewEnds]).
Usage (noise culled from shell output):
72> c("./f") % If `f.erl` is in the current dir that is.
73> F = f:curry(fun(A,B,C) -> A + B + C end).
74> F(1).
75> G = F(1).
76> G(2).
77> H = G(2).
78> H(3).
6
79> I = (F(1))(2).
80> I(3).
6
82> F2 = mtest:curry(fun erlang:'++'/2).
83> F2("lofa").
84> (F2("lofa"))("miez").
"lofamiez"
85> ((f:curry(fun lists:map/2))((f:curry(fun filename:join/2))("dir")))(["a_file", "b_file"]).
["dir/a_file","dir/b_file"]
Useful resources:
http://erlang.org/pipermail/erlang-questions/2005-April/015279.html
https://grantwinney.com/how-to-evaluate-a-string-of-code-in-erlang-at-runtime/
Convert erlang terms to string, or decode erlang binary
Erlang trying to evaluate a string
Knowing the number of parameters of a passed function (erlang)
https://erlang.org/doc/man/erl_eval.html
lists:foldl(
fun(Function,Accumulator) -> Function(Accumulator) end,
3,
[
fun(X) -> modname:add(3, X) end,
fun(X) -> modname:multiply(5, X) end
]
).

Printing in Haskell

I have a function that returns Floats (or some other type). I am using my program as a module in ghci. How would I print out info at certain points in the program? For example, if I detect bad input to a function, how do I print out an error message?
There are a few cases here, depending on what you want to do.
The straight forward sprinkling of printfs as a method of debugging is not going to work very well in Haskell.
If you have a partial function, I would suggest using Either or Maybe as a solution.
For example:
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
lookup x [] = Nothing
lookup x ((k,v):ys) | x == k = Just v
| otherwise = lookup x ys
lookup takes a key, and a list of key-value pairs and return Just the value associated with that key, or Nothing if the key is not in the list.
doMath :: Char -> Int -> Int -> Either String Int
doMath '+' x y = Right (x + y)
doMath '*' x y = Right (x * y)
doMath '/' x 0 = Left "Division by zero"
doMath '/' x y = Right (x / y)
doMath '-' x y = Right (x - y)
doMath c x y = Left ("Bad operator: " ++ show c)
Either is like maybe, in that if you can, you will return the right result. Otherwise you take what's left.
If your function really has an impossible case, then you can use the function error, which throws a pretty much uncatchable error with a string. It's not pretty, but it will help point you in the right direction when doing a post-mortem after the impossible does happen.
Because there are no side effects in pure code, you basically have three options:
You can print an error message and throw an exception, which usually terminates the program unless you catch it:
myDiv x 0 = error "Division by zero"
myDiv x y = x / y
You can print an error message and return some value:
import Debug.Trace
myDiv x y = trace ("Trying to divide " ++ show x ++ " by " ++ show y) (x / y)
You can return a value which describes the error in some way, e.g. Maybe or Either String:
myDivMaybe x 0 = Nothing
myDivMaybe x y = Just (x / y)
myDivEither x 0 = Left "Won't divide by zero"
myDivEither x y = Right (x / y)
You usually use error when the input is really invalid and you don't mind a runtime error in that case. trace is usually used for debugging purposes. If you want to avoid runtime errors on invalid input, you can use Maybe or Either.

Resources