Haskell - 使用与其他函数不同的函数 [英] Haskell - Make a function with one case difference from an other function

查看:78
本文介绍了Haskell - 使用与其他函数不同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  type Foo a = String  - >>我有一个关于如何更改这个结构的例子的问题。 ; 
- 让我们定义一个函数。
foo :: Foo Int
fooa= 5
foob= 6
fooc= 7
foo x = 0

现在假设我想创建另一个函数,它给了我另一个函数
但只在一种情况下更改,这是我所做的。

  changeFoo :: Foo a  - >字符串 - > a  - > Foo a 
changeFoo = \foo - > \str - > \x - > (\str-> \x)

我是编程Haskell的新手,似乎并没有改变这个功能的一个例子。如果有人能告诉我该怎么做,我会很感激。



预先致谢。

解决方案

您需要检查字符串是否相等。类似于

  changeFoo ::(String  - > Int) - >字符串 - > Int  - >字符串 - > Int 
changeFoo f s1 a s2
| s1 == s2 = a
|否则= f s2

我认为changeFoo可以被赋予一个更一般的类型:

  changeFoo :: Eq a => (a  - > b) - > a  - > b  - > a  - > b 

更通用的另一种写法是使用可能的类型:

  changeFoo ::(a  - > b) - > (a  - >可能b) - > a  - > b 

但这显然需要不同的实现。

I have a question about on how to change only one case of this structure:

type Foo a = String -> a
--Let's define a function.
foo :: Foo Int
foo "a" = 5
foo "b" = 6
foo "c" = 7
foo x = 0

Now suppose I want to create another function that gives me another function but only changed in one case, this is what I did.

changeFoo :: Foo a -> String -> a -> Foo a
changeFoo = \foo -> \str -> \x -> (\str -> \x)

I'm new at programming Haskell and this doesn't seem to change only one case of the function. If someone can tell me what to do I'll be grateful.

Thanks in advance.

解决方案

You need to check if the strings are equal or not. Something like

changeFoo :: (String -> Int) -> String -> Int -> String -> Int
changeFoo f s1 a s2
    | s1 == s2 = a
    | otherwise = f s2

I think changeFoo can be given a more general type though:

changeFoo :: Eq a => (a -> b) -> a -> b -> a -> b

Another way to write it even more generically is with the maybe type:

changeFoo :: (a -> b) -> (a -> Maybe b) -> a -> b

But that will clearly require a different implementation.

这篇关于Haskell - 使用与其他函数不同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆